Hemant Patil Hemant Patil - 1 month ago 9
Ruby Question

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

Suppose I have this array of hashes:

[ {"nutrient"=>"protein", "value"=>12, "calories"=>48, "unit"=>"g"},
{"nutrient"=>"fat", "value"=>5, "calories"=>45, "unit"=>"g"},
{"nutrient"=>"fibre", "value"=>1, "calories"=>nil, "unit"=>"g"},
{"nutrient"=>"carbohydrates", "value"=>67, "calories"=>268, "unit"=>"g"},
{"nutrient"=>"calcium", "value"=>42, "calories"=>nil, "unit"=>"mg"}]


How can I return boolean true if (nutrient value is equal to 'carbohydrates' and it's calories are equal to 268 ) and (if nutrient value is equal to 'protein' and it's calories are equal to 48)

That is, in short I want to return true for above array of hash.

Answer

Assuming that the nutrient values are unique, you could build a calories hash via:

calories = a.each_with_object({}) { |e, h| h[e['nutrient']] = e['calories'] }
#=> {"protein"=>48, "fat"=>45, "fibre"=>nil, "carbohydrates"=>268, "calcium"=>nil}

And check for the values via:

calories['carbohydrates'] == 268 && calories['protein'] == 48
#=> true