Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: select a hash from inside an array

Tags:

ruby

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

like image 940
deb Avatar asked Aug 05 '10 20:08

deb


People also ask

What does .select do in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

How do you turn an Array into a hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.


2 Answers

response.find {|x| x['label'] == 'cat' } #=> {"label"=>"cat", "name"=>"kitty", "id"=>189955}
like image 127
Adrian Avatar answered Sep 25 '22 01:09

Adrian


Try:

response.select { |x| x["label"] == "cat" }
like image 29
Daniel O'Hara Avatar answered Sep 25 '22 01:09

Daniel O'Hara