New way of creating hashes in ruby 2.2.0

前端 未结 1 1031
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 10:57

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_         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 11:13

    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)

    0 讨论(0)
提交回复
热议问题