-1

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"]
};
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
JhonDoe
  • 27
  • 6
  • It's easy to grab data when you have a fixed data structure, but how do you know you need "colder" rather than "big" or "brown"? Is your selection positional, word-matching, or what? – Todd A. Jacobs Jan 06 '21 at 17:07
  • Do you know how to access a value in a hash? Do you know how to access a value in an array? – Jörg W Mittag Jan 06 '21 at 17:28

1 Answers1

3

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"
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 1
    `planets.dig('jupiter',2)` and `planets['jupiter'].find { _1.match? /colder/i }` are worthy additions as well. BTW I love your use of numbered block parameters. – engineersmnky Jan 06 '21 at 19:34