2

I have a hash that looks something like this:

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"
        },
   }
}

I'm trying to get the value from "id" that matches a given key:

def get_champion_name_from_id(key)
    filtered = @champion_data["data"].select do | key, champ_data |
        Integer(champ_data["key"]) == key
    end     
end

I'm using select to get the items that match the block, however, the return value is another hash that looks like this:

{ 
    "Aatrox": {
        "id" => "Aatrox",
        "key" => "266",
        "name" => "Aatrox"
    } 
}

How can I avoid this and get just the last nested hash? If the key passed was 266, I want to get this hash:

{
    "id" => "Aatrox",
    "key" => "266",
    "name" => "Aatrox"
} 

This hash is the result of a parsed JSON file, so there's no way I can do filtered["Aatrox"] to get a given value.

0

2 Answers 2

7

Hash#values returns values only (without keys). And by using Enumerable#find, you will get the first matched item instead of an array that contains a single item.

@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
Sign up to request clarification or add additional context in comments.

1 Comment

This is great, much cleaner than what I was trying, thanks a lot!
0

You can do it with the select method also:

@champion_data["data"].select do |key, val|
  @champion_data["data"][key] if @champion_data["data"][key]["key"] == "266"
end

1 Comment

This returns the same result, another nested hash, which is not what I'm looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.