从 Ruby 中的变量创建哈希键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21440745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:22:50  来源:igfitidea点击:

Creating a hash key from a variable in Ruby?

rubyhashsyntax

提问by James McMahon

I have a variable idand 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.

我有一个变量id,我想将它用作散列中的键,以便将分配给该变量的值用作散列的键。

For instance, if I have the variable id = 1the desired resulting hash would be { 1: 'foo' }.

例如,如果我有变量,id = 1则所需的结果散列将是{ 1: 'foo' }.

I've tried creating the hash with,

我试过用,

{
  id: 'foo'
}

But that doesn't work, instead resulting in a hash with the symbol :idto 'foo'.

但这不起作用,而是导致散列符号:id为 to 'foo'

I could have sworn I've done this before but I am completely drawing a blank.

我可以发誓我以前做过这件事,但我完全画了一个空白。

回答by Gumbo

If you want to populate a new hash with certain values, you can pass them to Hash::[]:

如果要使用某些值填充新哈希,可以将它们传递给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'也可以用于{}

{ id => 'foo' }

Otherwise, if the hash already exists, use Hash#=[]:

否则,如果哈希已经存在,请使用Hash#=[]

h = {}
h[id] = 'foo'