tags:

views:

45

answers:

2

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

+4  A: 
response.find {|x| x['label'] == 'cat' } #=> {"label"=>"cat", "name"=>"kitty", "id"=>189955}
Adrian
that's exactly what I needed! thanks!
deb
+2  A: 

Try:

response.select { |x| x["label"] == "cat" }
floatless
select works too, but it returns an array, so I'm going with "find" in this particular case. Thanks! :)
deb
Yes, `Array#find` returns the first match or nil, while `Array#select` and `Array#find_all` return an array of all matching elements.
Andreas
And it's also worth noting that a synonym for `Array#find` is `Array#detect`.
PreciousBodilyFluids
thanks for all the extra info, you guys are the best ;)
deb