在Ruby中从变量创建一个散列键? [英] Creating a hash key from a variable in Ruby?
问题描述
我有一个变量 id
,我想用它作为哈希键,这样分配给变量的值就可以用作哈希键。 / p>
例如,如果我有变量 id = 1
,则所需的结果散列值将为 {1:'foo'}
。
我已经尝试创建哈希,
{
id:'foo'
}
但这不起作用,取而代之的是使用符号:id
到'foo'
。
我可以发誓我之前完成了这个工作,但我完全画空白。
如果你想用特定值填充一个新的散列,你可以将它们传递给 Hash :: []
:
哈希[a,100,b,200]#=> {a=> 100,b=> 200}
Hash [[[a,100],[b,200]]]#=> {a=> 100,b=> 200}
哈希[a=> 100,b=> 200]#=> {a=> 100,b=> 200}
:
Hash [id,'foo']
Hash [[[id,'foo']]]
Hash [id => 'foo']
最后一个语法 id => 'foo'
也可以与 {}
一起使用:
{id => 'foo'}
否则,如果散列已经存在,请使用 Hash#= [] $ c
h = {}
h [id] ='foo'
I have a variable id
and I want to use it as a key in a hash so that the value assigned to the variable is used as key of the hash.
For instance, if I have the variable id = 1
the desired resulting hash would be { 1: 'foo' }
.
I've tried creating the hash with,
{
id: 'foo'
}
But that doesn't work, instead resulting in a hash with the symbol :id
to 'foo'
.
I could have sworn I've done this before but I am completely drawing a blank.
If you want to populate a new hash with certain values, you can pass them to Hash::[]
:
Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
So in your case:
Hash[id, 'foo']
Hash[[[id, 'foo']]]
Hash[id => 'foo']
The last syntax id => 'foo'
can also be used with {}
:
{ id => 'foo' }
Otherwise, if the hash already exists, use Hash#=[]
:
h = {}
h[id] = 'foo'
这篇关于在Ruby中从变量创建一个散列键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!