我有一个看起来像这样的哈希:
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"]
获得给定的值.
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