Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

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"]
};
question from:https://stackoverflow.com/questions/65598607/access-a-specific-value-in-ruby-hash-with-multiple-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...