How about this?
Hash[a.flat_map(&:to_a).sort_by(&:last)]
=> {3=>12.4, 1=>19.4, 2=>59.4}
Here is a comparative comparison fruity:
require 'fruity'
a = 1000.times.collect { |i| { rand(100) => rand(1000) } }
compare do
caryswoveland {
a.group_by(&:keys).map {|k,v| {k.first => v.map(&:values).flatten.max}}
}
matt { a.group_by(&:keys).map { |k,v| v.max_by { |j| j[k[0]] } } }
steenslag {
a.each_with_object({}){|h, res|
res.merge!(h){|k, *vals| res[k] = vals.max}
}
}
abdo { Hash[a.flat_map(&:to_a).sort_by(&:last)] }
end
Conclusion:
Running each test 4 times. Test will take about 1 second.
abdo is similar to steenslag (results differ..)
steenslag is faster than matt by 30.000000000000004% ± 10.0%
matt is faster than caryswoveland by 30.000000000000004% ± 10.0%
source
share