Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between colon placement in :something and somethingelse: [duplicate]

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.

like image 950
Tom Avatar asked May 02 '12 13:05

Tom


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

like image 123
Jesse Wolgamott Avatar answered Oct 06 '22 01:10

Jesse Wolgamott


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

like image 27
Abid Avatar answered Oct 05 '22 23:10

Abid