我有一個哈希看起來是這樣的:選擇從嵌套的哈希值與未知鍵
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
我使用的選擇得到匹配塊的項目,然而,返回值是另一個哈希,看起來像這樣:
{
"Aatrox": {
"id" => "Aatrox",
"key" => "266",
"name" => "Aatrox"
}
}
我怎樣才能避免這種情況,並得到最後一個嵌套散列? 如果傳遞的關鍵是266,我想這個哈希:
{
"id" => "Aatrox",
"key" => "266",
"name" => "Aatrox"
}
這哈希值是一個解析的JSON文件的結果,所以沒有辦法,我可以做filtered["Aatrox"]
得到一個給定值。
這是偉大的,比我試圖乾淨多了,非常感謝! –