问题描述
:key => 之间有什么区别吗?"value"
(hashrocket) 和 key: "value"
(Ruby 1.9) 符号?
Is there any difference between :key => "value"
(hashrocket) and key: "value"
(Ruby 1.9) notations?
如果没有,那么我想使用 key: "value"
表示法.是否有宝石可以帮助我从 :x =>
转换为 x:
符号?
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
但这些不是:
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?' }
但你不能这样做:
h = { C.new: 11 }
h = { 23: 'pancakes house?' }
JavaScript 样式 (key: value
) 仅在所有哈希键都是简单"符号(或多或少与 /A[a-z_] 匹配的东西)时才有用w*z/i
,AFAIK 解析器对这些键使用其标签模式).
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).
:$in
样式符号在使用 MongoDB 时会显示一些,因此如果您使用 MongoDB,最终会混合哈希样式.而且,如果您曾经使用过哈希的特定键 (h[:k]
) 而不是整个哈希 (h = { ... }
),您将仍然必须对符号使用冒号优先样式;对于在哈希之外使用的符号,您还必须使用前导冒号样式.我更喜欢保持一致,所以我根本不关心 JavaScript 风格.
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.
JavaScript 风格的一些问题已在 Ruby 2.2 中得到修复.如果您的符号不是有效标签,您现在可以使用引号,例如:
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 } }
但如果你的键不是符号,你仍然需要 hashrocket.
But you still need the hashrocket if your keys are not symbols.
这篇关于`:key => 之间有什么区别吗?“值"和“键:"值“哈希符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!