我有一系列哈希,我想写一个通用的检查器,所以我想传入要检查的键的名称.散列是使用带冒号前缀(符号)的键定义的.我无法弄清楚如何正确使用变量作为键.即使密钥存在于散列中,使用变量访问它也会导致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?