What does :this means in Ruby on Rails?

A colon before text indicates a symbol in Ruby. A symbol is kind of like a constant, but it's almost as though a symbol receives a unique value (that you don't care about) as its constant value.

When used as a hash index, symbols are almost (but not exactly) the same as using strings.

Also, you can read "all" from :all by calling to_s on the symbol. If you had a constant variable ALL, there would be no way to determine that it meant "all" other than looking up its value. This is also why you can use symbols as arguments to meta-methods like attr_accessor, attr_reader, and the like.

You might want to read up on Ruby symbols.


:all is a symbol. Symbols are Ruby's version of interned strings. You can think of it like this: There is an invisible global table called symbols which has String keys and Fixnum values. Any string can be converted into a symbol by calling .to_sym, which looks for the string in the table. If the string is already in the table, it returns the the Fixnum, otherwise, it enters it into the table and returns the next Fixnum. Because of this, symbols are treated at run-time like Fixnums: comparison time is constant (in C parlance, comparisons of symbols can be done with == instead of strcmp)

You can verify this by looking at the object_id of objects; when two thing's object_ids are the same, they're both pointing at the same object.

You can see that you can convert two strings to symbols, and they'll both have the same object id:

"all".to_sym.object_id == "all".to_sym.object_id #=> true

"all".to_sym.object_id == :all.object_id #=> true

But the converse is not true: (each call to Symbol#to_s will produce a brand new string)

:all.to_s.object_id == :all.to_s.object_id #=> false


Don't look at symbols as a way of saving memory. Look at them as indicating that the string ought to be immutable. 13 Ways of Looking at a Ruby Symbol gives a variety of ways of looking at a symbol.

To use a metaphor: symbols are for multiple-choice tests, strings are for essay questions.

Tags:

Ruby

Symbols