我有一个哈希数组来编写通用检查程序,因此我想传递要检查的键的名称。哈希是用带有符号(冒号前缀)的键定义的。我不知道如何正确使用变量作为键。即使键存在于哈希中,使用变量访问它也将导致nil。

在IRB中,我这样做:

>> family = { 'husband' => "Homer", 'wife' => "Marge" }
=> {"husband"=>"Homer", "wife"=>"Marge"}
>> somevar = "husband"
=> "husband"
>> family[somevar]
=> "Homer"
>> another_family  = { :husband => "Fred", :wife => "Wilma" }
=> {:husband=>"Fred", :wife=>"Wilma"}
>> another_family[somevar]
=> nil
>>

如何通过变量访问哈希键?也许另一种询问方式是,如何将变量强制为符号?

最佳答案

您要先将字符串转换为符号:

another_family[somevar.to_sym]

如果您不必担心哈希是符号还是字符串,只需将其转换为符号键

请参阅:How do I convert a Ruby hash so that all of its keys are symbols?

09-25 17:58