Ruby 中的符号和变量有什​​么区别? [英] What is the difference between a symbol and a variable in Ruby?

查看:35
本文介绍了Ruby 中的符号和变量有什​​么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 ruby​​ 中符号和变量之间的区别.他们似乎在给出一个引用对象的名称时做完全相同的事情.

I am trying to understand what the difference is between a symbol and a variable in ruby. They seemed to do the exact same thing in giving a name that references an object.

我已经为更快的程序阅读了这些符号,但我不确定它们为什么或如何与变量有任何不同.

I have read that symbols alow for faster programs but I am not sure why or how they are different from variables in any way.

推荐答案

符号是一个内部化"的字符串,它更像是一个常数而不是任何东西.典型例子:

A symbol is an "internalized" string, it's more like a constant than anything. Typical example:

account_details = {
  :name => 'Bob',
  :age => 20
}

这里的符号 :name:age 是散列的键.不要将它们与变量混淆.account_details 是一个变量.

Here the symbols :name and :age are keys for a hash. They are not to be confused with variables. account_details is a variable.

Ruby 中的变量是某种对象的句柄,该对象可能是一个符号.

A variable in Ruby is a handle to an object of some sort, and that object may be a symbol.

通常在使用字符串时使用符号会导致大量重复.请记住,字符串通常是不同的对象,其中不同的符号总是指同一个对象,如果经常使用,它们会更有效率.

Normally you employ symbols when using strings would result in a lot of repetition. Keep in mind that strings are generally distinct objects where a distinct symbol always refers to the same object, making them more efficient if used frequently.

比较:

"string".object_id == "string".object_id
# => false

:string.object_id == :string.object_id
# => true

即使这两个字符串相同,它们也是独立的字符串对象.当用作散列的键、方法的参数和其他常见情况时,除非您特意使用相同的字符串实例,否则这些对象将很快因大量重复而使您的内存变得混乱.符号会自动为您执行此操作.

Even though those two strings are identical, they're independent string objects. When used as keys for hashes, arguments to methods, and other common cases, these objects will quickly clutter up your memory with massive amounts of duplication unless you go out of your way to use the same string instance. Symbols do this for you automatically.

这篇关于Ruby 中的符号和变量有什​​么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆