27

I have the following array:

response = [{"label"=>"cat", "name"=>"kitty", "id"=>189955}, {"label" => "dog", "name"=>"rex", "id" => 550081}]

How do I select the hash that contains the label cat? I know response.first will give me the same result, but I want to search the by label.

Thanks!

Deb

2 Answers 2

49
response.find {|x| x['label'] == 'cat' } #=> {"label"=>"cat", "name"=>"kitty", "id"=>189955}
Sign up to request clarification or add additional context in comments.

Comments

15

Try:

response.select { |x| x["label"] == "cat" }

3 Comments

select works too, but it returns an array, so I'm going with "find" in this particular case. Thanks! :)
Yes, Array#find returns the first match or nil, while Array#select and Array#find_all return an array of all matching elements.
And it's also worth noting that a synonym for Array#find is Array#detect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.