Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the bigger value for each key in a list of hashes in Ruby

I can imagine there is a simple way to do that instead of use many variables and state.

I just want to get the highest value given for each key in a list of hashes

For example:

[{1=>19.4}, {1=>12.4}, {2=>29.4}, {3=>12.4}, {2=>39.4}, {2=>59.4}]

Result

[{1=>19.4}, {3=>12.4}, {2=>59.4}]
like image 741
coffee Avatar asked Jan 22 '26 22:01

coffee


2 Answers

I'd do as below :

a = [{1=>19.4}, {1=>12.4}, {2=>29.4}, {3=>12.4}, {2=>39.4}, {2=>59.4}]

# the below is the main trick, to group the hashes and sorted the key/value pair
# in **ascending order**.
a.sort_by(&:to_a)
# => [{1=>12.4}, {1=>19.4}, {2=>29.4}, {2=>39.4}, {2=>59.4}, {3=>12.4}]

# then using the trick in mind, we know hash can't have duplicate keys, so
# blindly I can rely on `Enumerable#inject` with the `Hash#merge` method.
a.sort_by(&:to_a).inject(:merge)
# => {1=>19.4, 2=>59.4, 3=>12.4}

# final one
a.sort_by(&:to_a).inject(:merge).map { |k,v| {k => v} }
# => [{1=>19.4}, {2=>59.4}, {3=>12.4}]
like image 126
Arup Rakshit Avatar answered Jan 25 '26 14:01

Arup Rakshit


This is a variant of @Matt's answer:

 a.group_by(&:keys).map {|k,v| {k.first => v.map(&:values).flatten.max}}
   #=> [{1=>19.4}, {2=>59.4}, {3=>12.4}]
like image 38
Cary Swoveland Avatar answered Jan 25 '26 12:01

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!