Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

Why are symbols in Ruby not thought of as a type of variable?

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.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Symbols are not variables, but a type of literal value, like numerals and quoted strings. Significantly, symbols are used to represent variables and other named values in the Ruby runtime. So when the Ruby interpreter sees the name foo used as a variable or method name, what it looks up in the Hash of runtime values is the symbol :foo, not the string "foo". This was, in fact, the original use of the term "symbol" in programming language terminology; variables, functions, constants, methods, and so on are said to be stored in the compiler or interpreter's "symbol table".

Pretty much any time you're passing around the name of something in Ruby, you're going to use a symbol. If you use method_missing as a catch-all to implement arbitrary methods on your object class, a symbol is what it receives as an argument telling it the name of the method that was actually called. If you inspect an object with .methods or .instance_variables, what you get back is an array of symbols. And so on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...