Ruby Easy Search for Key-Value Pair in an Array of Hashes

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

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"

search for matching key-value pair in an array of hashes and return true if match found

a.count do |hash|
(hash['nutrient'] == 'carbohydrates' && hash['calories'] == 268) || (hash['nutrient'] == 'protein' && hash['calories'] == 48)
end == 2

What this does, is it counts any element in the collection, that passes EITHER this condition:

hash['nutrient'] == 'carbohydrates' && hash['calories'] == 268

OR this one

hash['nutrient'] == 'protein' && hash['calories'] == 48

And it returns true if there are exactly two matches.

How to search for a hash key value in an array of hashes

find returns a hash in your case, just pass the key :place to get the value:

hash = array.find {|x| x[:name] == "John"}
return if hash.nil?
hash[:place]

Regarding the query about mixed values, I just tried it in IRB and it worked fine.

2.7.0 :014 > array = [
2.7.0 :015 > {:name => "Bob" , :age => 27 , :place => "A"} ,
2.7.0 :016 > {:name => "John" , :age => 50 , :place => "B"} ,
2.7.0 :017 > {:name => "Alex" , :age => 80 , :place => "C"}
2.7.0 :018 > ]
2.7.0 :019 > array.find {|x| x[:name] == "John"}
=> {:name=>"John", :age=>50, :place=>"B"}

Select key value pairs from a hash whose keys belong to an array

Try this:

hsh.select{ |k, v| keys.include?(k) } 

Add key value pair to Array of Hashes when unique Id's match

For reasons of both efficiency and readability, it makes sense to first construct a lookup hash on active_array:

h = active_array.each_with_object({}) { |g,h| h[g[:asin1]] = g[:price] } 
#=> {"B00ND80WKY"=>39.99, "B00YSN9QOG"=>7.99, "B00HXZLB4E"=>10}

We now merely step through sent_array, updating the hashes:

sent_array.each { |g| g[:price] = h[g[:asin]] if h.key?(g[:asin]) }
#=> [{:sellersku=>"0421077128", :asin=>"B00ND80WKY", :price=>39.99},
# {:sellersku=>"0320248102", :asin=>"B00WTEF9FG"},
# {:sellersku=>"0324823180", :asin=>"B00HXZLB4E", :price=>10}]

Retrieving a key-value pair from a hash (h) is much faster, of course, than searching for a key-value pair in an array of hashes.

How do you grab a key/value pair from an array of hashes in ruby?

To pull out just the IDs you can do this:

the_IDs = array_of_hashes.collect { |single_array| single_array["id"] }

Obviously you can use less verbose variable names, they're just for illustration. But the idea is that you can loop through an array and collect whatever the block returns. In this case, you keep getting an ID returned, and the_IDs will just be an array of what was collected.

Get a value from an array of hashes in ruby

The select statement will return all the hashes with the key 13.

If you already know which hash has the key then the below code will give u the answer.

ary[1][13]

However if you are not sure which of your hashes in the array has the value, then you could do the following:

values = ary.map{|h| h[13]}.compact

Values will have the value of key 13 from all the hashes which has the key 13.



Related Topics



Leave a reply



Submit