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"]
};
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.
Before doing anything else, fix your invalid hash. For example:
planets = {
"jupiter" => ["brown", "big", "colder"],
"mars" => ["red", "small", "cold"],
}
Select your key, then the last element. Examples include:
planets['jupiter'][2]
#=> "colder"
planets['jupiter'][-1]
#=> "colder"
planets['jupiter'].last
#=> "colder"
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"