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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With