Search code examples
rubyruby-hash

Access a specific value in ruby hash with multiple values


Hi how can I access a specific value in ruby hash, for example how can i get "colder" inside jupiter

planets= {
"jupiter" => ["brown", "big" , "colder"]
"mars" => ["red", "small", "cold"]
};

Solution

  • Focus on Intent

    There's definitely more than one way to do this, so the key is to focus less in the result (although getting the right result is important) and more on effectively expressing your intent with the code. All of the examples provided below (and others besides) will give you the right result, but the approach and semantics are all slightly different. Always pick the approach that most closely matches what you're trying to say.

    Fix Your Hash

    Before doing anything else, fix your invalid hash. For example:

    planets = {
      "jupiter" => ["brown", "big", "colder"],
      "mars"    => ["red", "small", "cold"],
    }
    

    Positional Selection

    Select your key, then the last element. Examples include:

    planets['jupiter'][2]
    #=> "colder"
    
    planets['jupiter'][-1]
    #=> "colder"
    
    planets['jupiter'].last
    #=> "colder"
    

    Content-Based Selection

    If you don't know which element you want to select from the nested array, you'll need to use some form of matching to find it. Examples can include:

    planets['jupiter'].grep(/colder/).pop
    #=> "colder"
    
    planets['jupiter'].grep(/colder/).first
    #=> "colder"
    
    planets['jupiter'].grep(/colder/)[0]
    #=> "colder"
    
    planets['jupiter'].select { _1.match? /colder/ }.pop
    #=> "colder"