`:key =>是否有区别? "值"&key:" value"哈希符号? [英] Is there any difference between the `:key => "value"` and `key: "value"` hash notations?
问题描述
:key =>之间是否有区别? value
(hashrocket)和 key:value
(Ruby 1.9)符号?
如果不是,那么我想用键:value
表示法。是否有帮助我从:x =>
转换为 x:
符号的gem?
是的,存在差异。这些是合法的:
h = {:$ in => array}
h = {:'a.b'=> 'c'}
h [:s] = 42
但这些不是:
h = {$ in:array}
h = {'a.b':'c'}#但这是可以在Ruby2.2 +
h中使用[s:] = 42
作为 =>>
的关键,所以你可以这样做:
h = {C.new => 11}
h = {23 => 'pancakes house?'}
但是您不能这样做:
h = {C.new:11}
h = {23:'煎饼屋?'}
JavaScript样式( key:value
)仅在所有Hash键都是简单符号(或多或少与 / \ A [a-z_] \ w \\ \ z / i
相匹配的东西,AFAIK解析器使用它的标签模式对于这些键)。
使用MongoDB时,:$ in
样式符号显示出合理的位,如果您使用MongoDB,最终会混合哈希样式。而且,如果您曾经使用Hashes的特定键( h [:k]
)而不是整个哈希( h = {...}
),您仍然必须使用符号的冒号优先样式;您还必须使用引号分隔样式来表示您在哈希之外使用的符号。我更喜欢保持一致性,所以我根本不打扰JavaScript风格。
在Ruby 2.2中,JavaScript风格的一些问题已得到解决。如果您的符号不是有效标签,您现在可以使用引号,例如:
h = {'其中是' :'pancakes house?','$ set':{a:11}}
但你仍然如果你的钥匙不是符号的话,需要使用hashrocket。
Is there any difference between :key => "value"
(hashrocket) and key: "value"
(Ruby 1.9) notations?
If not, then I would like to use key: "value"
notation. Is there a gem that helps me to convert from :x =>
to x:
notations?
Yes, there is a difference. These are legal:
h = { :$in => array }
h = { :'a.b' => 'c' }
h[:s] = 42
but these are not:
h = { $in: array }
h = { 'a.b': 'c' } # but this is okay in Ruby2.2+
h[s:] = 42
You can also use anything as a key with =>
so you can do this:
h = { C.new => 11 }
h = { 23 => 'pancakes house?' }
but you can't do this:
h = { C.new: 11 }
h = { 23: 'pancakes house?' }
The JavaScript style (key: value
) is only useful if all of your Hash keys are "simple" symbols (more or less something that matches /\A[a-z_]\w*\z/i
, AFAIK the parser uses its label pattern for these keys).
The :$in
style symbols show up a fair bit when using MongoDB so you'll end up mixing Hash styles if you use MongoDB. And, if you ever work with specific keys of Hashes (h[:k]
) rather than just whole hashes (h = { ... }
), you'll still have to use the colon-first style for symbols; you'll also have to use the leading-colon style for symbols that you use outside of Hashes. I prefer to be consistent so I don't bother with the JavaScript style at all.
Some of the problems with the JavaScript-style have been fixed in Ruby 2.2. You can now use quotes if you have symbols that aren't valid labels, for example:
h = { 'where is': 'pancakes house?', '$set': { a: 11 } }
But you still need the hashrocket if your keys are not symbols.
这篇关于`:key =>是否有区别? "值"&key:" value"哈希符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!