A new way to create 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 can not understand the reason for the implementation of this style. If I need a string as a key (for example, for some third-party library), I still have to use an old-style hash. What are the options for using this "feature"? Why did the main developers add this style?

Thanks in advance.

+6
source share
1 answer

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

In 1.9 you can do it

 hash = { symbol_key: 'value' } 

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

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

However, in versions 1.9 through 2.1, the code

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

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

Adding support for the quoted wrapper around Symbol in the hash syntax is likely to be consistent. Options when writing a character literal with short hash key syntax are now the same as when writing the same literal outside the hash (except where you put the colon)

+10
source

Source: https://habr.com/ru/post/980479/


All Articles