本文介绍了Ruby 和 :symbols的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我刚刚开始使用 Ruby,我正在阅读Programming Ruby 1.9 - The Pragmatic Programmer's Guide".我遇到了一种叫做符号的东西,但作为一名 PHP 开发人员,我不明白它们的作用和用途.

I have just started using Ruby and I am reading "Programming Ruby 1.9 - The Pragmatic Programmer's Guide". I came across something called symbols, but as a PHP developer I don't understand what they do and what they are good for.

谁能帮我解决这个问题?

Can anyone help me out with this?

推荐答案

根据被调用的事物"来考虑符号很有用.换句话说, :banana 指的是那种叫做香蕉的东西".它们在 Ruby 中被广泛使用,主要用作哈希(关联数组)键.

It's useful to think of symbols in terms of "the thing called." In other words, :banana is referring to "the thing called banana." They're used extensively in Ruby, mostly as Hash (associative array) keys.

它们确实类似于字符串,但在幕后,却大不相同.一个关键的区别是内存中只存在一个特定符号.因此,如果您在代码中引用 :banana 10 次,则只会创建一个 :banana 实例,并且它们都引用了那个实例.这也意味着它们是不可变的.

They really are similar to strings, but behind the scenes, very different. One key difference is that only one of a particular symbol exists in memory. So if you refer to :banana 10 times in your code, only one instance of :banana is created and they all refer to that one. This also implies they're immutable.

这篇关于Ruby 和 :symbols的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:41