我有一个看起来像这样的哈希:
hash = { "data" => {
"Aatrox" => {
"id" => "Aatrox",
"key" => "266",
"name" => "Aatrox"
},
"Ahri" => {
"id" => "Ahri",
"key" => "123",
"name" => "Ahri"
},
"Another name" => {
"id" => "Another name",
"key" => "12",
"name" => "Another name"
},
}
}
我试图从" id"中获取价值。匹配给定键:
def get_champion_name_from_id(key)
filtered = @champion_data["data"].select do | key, champ_data |
Integer(champ_data["key"]) == key
end
end
我使用select来获取与块匹配的项,但是,返回值是另一个看起来像这样的哈希:
{
"Aatrox": {
"id" => "Aatrox",
"key" => "266",
"name" => "Aatrox"
}
}
如何避免这种情况并获得最后一次嵌套哈希? 如果传递的密钥是266,我想得到这个哈希:
{
"id" => "Aatrox",
"key" => "266",
"name" => "Aatrox"
}
此哈希是解析后的JSON文件的结果,因此我无法filtered["Aatrox"]
来获取给定值。
答案 0 :(得分:5)
Hash#values
仅返回值(不带键)。通过使用Enumerable#find
,您将获得第一个匹配的项目,而不是包含单个项目的数组。
@champion_data['data'].values.find { |champ_data|
champ_data['key'] == '266'
}
# => {"id"=>"Aatrox", "key"=>"266", "name"=>"Aatrox"}
def get_champion_name_from_id(key)
key = key.to_s
@champion_data['data'].values.find { |champ_data|
champ_data['key'] == key
}
end
答案 1 :(得分:0)
您也可以使用select
方法执行此操作:
@champion_data["data"].select do |key, val|
@champion_data["data"][key] if @champion_data["data"][key]["key"] == "266"
end