问题描述
在ruby 2.2.0中,你可以这样写哈希值: hash = {'new_possible_style'::of_hashes}
hash [:new_possible_style]#=> :of_hashes
hash ['new_possible_style']#=>无
我无法理解实现这种风格的原因。如果我需要字符串作为键(例如,对于某些第三方库),我仍然必须使用旧式散列。这个'功能'的用例是什么?为什么核心开发人员添加这种风格?
在此先感谢您。
这不是一种新的哈希表示形式,而是以一致的方式添加到1.9中的现有样式的扩展。
在1.9中,您可以这样做
hash = {symbol_key:'value'}
,您还可以使用以下语法定义 Symbol
s以及其他受限制的字符:
sym =:'a-symbol-with-dashes'
然而,在版本1.9到2.1中,代码
hash = {'a-symbol-with-破折号':'value'}
不被识别为有效的语法,相反,它会得到异常 SyntaxError:(irb):4:syntax error,unexpected':',expecting =>
引用在散列语法中包含 Symbol
最可能的一致性。使用短散列键语法编写Symbol文字时的选项现在与在散列之外编写相同的文字时相同(除了放置冒号的地方)
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.
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 Symbol
s 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)
这篇关于在ruby 2.2.0中创建哈希的新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!