为什么 Ruby 中的符号不​​被认为是一种变量? [英] Why are symbols in Ruby not thought of as a type of variable?

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

问题描述

编程和 Ruby 的新手,我希望这个关于符号的问题是一致的.我知道 Ruby 中的符号(例如,:book:price)特别适合用作散列键,并且可以全方位地执行轻量级的特定子集字符串可以做到.

New to programming and to Ruby, and I hope this question about symbols is in line. I understand that symbols in Ruby (e.g., :book, :price) are useful particularly as hash keys, and for all-around doing a lightweight, specific subset of the things that strings can do.

然而,我在一方面对符号感到困惑.具体来说,当它们在 attr_accessor 类型的方法中使用时,它们的行为似乎更像是一个变量.例如,attr_reader :book, :price.

However, I am confused about symbols in one respect. Specifically, when they're used in the attr_accessor types of methods, it appears that they are behaving more like a variable. E.g., attr_reader :book, :price.

如果它们是该用法中的变量,这有点令人费解,因为它们通常不会列在变量类型中(例如 $global、@instance、local、@@class,有时还有 CONSTANT 变量类型)描述变量类型时.

If true that they are variables in that usage, this is a bit puzzling because they are not typically listed among variable types (like the $global, @instance, local, @@class, and sometimes, CONSTANT, variable types) when variables types are described.

如果以这种方式使用符号是变量,那么它们的作用域应该是什么?或者在这种情况下它们仍然以某种方式轻量级字符串?(或者更广泛地说,符号、字符串和变量是否都具有基本的类似鸭子的性质?)在此先感谢您的见解和建议.

And if symbols are variables when used this way, what scope should be expected of them? Or are they still somehow lightweight strings in this context as well? (Or perhaps in some broader way, do symbols, strings, and variables all share a fundamental duck-like nature?) Thank you in advance for your insights and advice.

推荐答案

访问器方法中使用的符号不是变量.它们只是代表一个变量的名称.变量持有一些引用,因此您不能在定义访问器方法时使用变量本身.例如,假设您想在其值为 "bar" 的上下文中为变量 @foo 定义访问器方法.如果 Ruby 的语法是这样的,会发生什么:

Symbols used in accessor methods are not variables. They are just representing the name of a variable. Variables hold some reference, so you cannot use a variable itself in defining accessor methods. For example, suppose you wanted to define an accessor method for the variable @foo in a context where its value is "bar". What would happen if Ruby's syntax were to be like this:

attr_accessor @foo

这与写作没有什么不同:

This would be no different from writing:

attr_accessor "bar"

您无法访问您感兴趣的名称 @foo.因此,此类结构必须设计为在元级别引用变量名称.为此使用符号.它们本身不是变量.它们代表变量的名称.

where you have no access to the name @foo that you are interested in. Therefore, such constructions have to be designed to refer to variable names at a meta level. Symbol is used for this reason. They are not variables themselves. They represent the name of a variable.

与访问器方法相关的变量是实例变量.

And the variable relevant to accessor methods are instance variables.

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

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