Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New way of creating hashes in ruby 2.2.0

Tags:

ruby

hash

In ruby 2.2.0 you can write hashes like this:

hash = { 'new_possible_style': :of_hashes }
hash[:new_possible_style]  #=> :of_hashes
hash['new_possible_style'] #=> nil 

I cannot realise the reason for implementing this style. If I need string as key(for instance, for some third party library), I still have to use old-style hash. What the use cases for this 'feature'? Why did core-developers add this style?

Thanks in advance.

like image 346
Alexander Karmes Avatar asked Jan 03 '15 21:01

Alexander Karmes


Video Answer


1 Answers

This is not a new style of hash representation, but an extension of the existing style added in 1.9 in a consistent manner.

In 1.9, you can do this

hash = { symbol_key: 'value' }

and you can also define Symbols with otherwise-restricted characters using syntax like this:

sym = :'a-symbol-with-dashes'

However in versions 1.9 to 2.1, the code

hash = { 'a-symbol-with-dashes': 'value' }

is not recognised as valid syntax, instead it you get the exception SyntaxError: (irb):4: syntax error, unexpected ':', expecting =>

Adding support for quoted wrapping around the Symbol in the hash syntax is most likely for consistency. The options when writing a Symbol literal with the short hash key syntax are now the same as when writing the same literal outside of the hash (other than where you put the colon)

like image 148
Neil Slater Avatar answered Sep 27 '22 23:09

Neil Slater