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
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.
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.
response.find {|x| x['label'] == 'cat' } #=> {"label"=>"cat", "name"=>"kitty", "id"=>189955}
Try:
response.select { |x| x["label"] == "cat" }
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