I am struggling to understand difference between :symbol and text: with regards to the colon placement. My understanding is that when we use :symbol we are referring to this object and whatever it contains, where as text: is used to assign a value to the text like we would a variable. Is this correct or could someone elaborate on the usage. Thank you.
-
1Symbol : value only appears in hash expression as a way to shorten it but I did not find many people favor it. – SwiftMango May 02 '12 at 13:56
2 Answers
:whatever
is a symbol, you've got that part right.
When you're using a hash, this was how you used to define it in 1.8x ruby:
{:key => value, :another_key => another_value}
This is known as the hashrocket syntax. In ruby 1.9x, this changed to:
{key: value, another_key: another_value}
There is backward compatibility that will still load the hashrocket syntax... But, in 1.9, 'key:' is a symbol

- 40,197
- 4
- 83
- 109
-
2Your last statement will cause confusion..I dont think `key:` is a symbol in ruby,but when this syntax comes inside the braces, ruby identifies it as a symbol. Also the hashrocket syntax is not provided only for backward compatibility. Infact, if you want to define a hash with non symbol keys, you need to rely on hash rocket syntax. I would say the new json style syntax is more of a syntactic sugar. – rubyprince May 02 '12 at 19:33
the {:key => value}
is the old hash syntax in ruby, now we have a new hash syntax that is more like json so
{:key => value}
is the same as
{key: value}
The old one, we’re all familiar with is:
old_hash = {:simon => "Talek", :lorem => "Ipsum"}
This is all nice and dandy, but it could be simpler and cleaner. Check out the Ruby 1.9 style, it sort of resembles JSON:
new_hash = {simon: "Talek", lorem: "Ipsum"}
But now you look closer and ask, “But previously the key was a symbol explicitly, what’s with this now?”.
Well you’re right, the new notation is sort of a syntactic sugar for the most common style of hashes out there, the so called symbol to object hash. If you do this in the irb, you’ll see ruby returning the old school hash, with the symbols used as keys:
> new_hash = {simon: "Talek", lorem: "Ipsum"}
=> {:simon=>"Talek", :lorem=>"Ipsum"}
If you need to have arbitrary objects as your hash keys, you’ll still have to do it old school.
ref:http://breakthebit.org/post/8453341914/ruby-1-9-and-the-new-hash-syntax