Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a hash key value in an array of hashes

I have an array of hashes:

array = [
 {:name => "Bob" , :age => 27 , :place => "A"} ,
 {:name => "John" , :age => 50 , :place => "B"} ,
 {:name => "Alex" , :age => 80 , :place => "C"} 
]

I want to get the value of :place if :name == "John".

However, if I use

array.find {|x| x[:name] == "John"}

I get

{:name=>"John", :age=>"27", :place=>A}

I can use

array.second[:place]

which will return B, but the array will have more than three Hash elements.

How can I get the right place returned on the condition of another key's value?

like image 614
Demi Dimitrova Avatar asked Sep 03 '25 06:09

Demi Dimitrova


1 Answers

If one needs a single method call, they might cheat find with even earlier return.

array.find { |h| break h[:place] if h[:name] == 'John' }
#⇒ "B"
like image 147
Aleksei Matiushkin Avatar answered Sep 04 '25 20:09

Aleksei Matiushkin