Alexander
Alexander

Reputation: 2558

New way of creating hashes in ruby 2.2.0

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.

Upvotes: 6

Views: 1854

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

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)

Upvotes: 10

Related Questions