Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby easy search for key-value pair in an array of hashes

Tags:

arrays

ruby

Suppose I have this array of hashes:

[ {"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"}, {"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},  {"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"} ] 

How can I parse the "href" value of the hash where "product"=>"bcx"

Is there any easy way to do this in Ruby?

like image 607
Brian Weinreich Avatar asked May 14 '12 13:05

Brian Weinreich


People also ask

How do I get the key-value in Ruby?

You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.


1 Answers

ary = [   {"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"},   {"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},    {"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"} ]  p ary.find { |h| h['product'] == 'bcx' }['href'] # => "https://basecamp.com/123456789/api/v1" 

Note that this only works if the element exists. Otherwise you will be calling the subscription operator [] on nil, which will raise an exception, so you might want to check for that first:

if h = ary.find { |h| h['product'] == 'bcx' }   p h['href'] else   puts 'Not found!' end 

If you need to perform that operation multiple times, you should build yourself a data structure for faster lookup:

href_by_product = Hash[ary.map { |h| h.values_at('product', 'href') }] p href_by_product['campfire'] # => "https://company.campfirenow.com" p href_by_product['bcx']      # => "https://basecamp.com/123456789/api/v1" 
like image 128
Niklas B. Avatar answered Sep 30 '22 12:09

Niklas B.