Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of the new hash syntax in Ruby 1.9?

Apart from making it sightly more concise for defining hashes with symbols as keys, are there any other benefits of writing a hash as:

{key1: "value1", key2: "value2"} instead of {:key1 => "value1", :key2 => "value2"}?

Also, what is the convention when you have a mix of strings and symbols as hash keys?

Do you write it as {"key1" => "value1", key2: "value2"} or keep the style consistant as {"key1" => "value1", :key => "value2"}

like image 335
zsquare Avatar asked Jul 10 '12 11:07

zsquare


2 Answers

It just looks nicer--it's syntactic sugar; it ends up being the same thing.

When mixing keys (ew, why would you do that?) I use the old hash-rocket syntax for the entire hash.

With symbol values I also use the old hash-rocket syntax for the entire hash–this looks icky:

{ ohai: :kthxbye }

I don't like mixing the two styles in the same hash–I think it's confusing.

This is all based on personal preference, though.

like image 110
Dave Newton Avatar answered Nov 13 '22 03:11

Dave Newton


It's shorter, and similar to JavaScript notation. Not worth to migrate old notation to the new for any reason, but otherwise choose which you like.

Always keep the code consistent, don't mix notations. It's more readable that way.

like image 3
Matzi Avatar answered Nov 13 '22 05:11

Matzi