如何在Ruby中使用变量访问符号哈希键 [英] How to access a symbol hash key using a variable in Ruby

查看:130
本文介绍了如何在Ruby中使用变量访问符号哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of hashes to write a generic checker for, so I want to pass in the name of a key to be checked. The hash was defined with keys with symbols (colon prefixes). I can't figure out how to use the variable as a key properly. Even though the key exists in the hash, using the variable to access it results in nil.

在IRB中,我这样做:

In IRB I do this:

>> 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
>>

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

How do I access the hash key through a variable? Perhaps another way to ask is, how do I coerce the variable to a symbol?

推荐答案

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

You want to convert your string to a symbol first:

another_family[somevar.to_sym]

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

If you want to not have to worry about if your hash is symbol or string, simply convert it to symbolized keys

请参阅: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆