如何在Ruby中的哈希列表中为每个键提取更大的值

cof*_*fee 3 ruby collections hash functional-programming max

我可以想象有一种简单的方法可以做到这一点,而不是使用许多变量和状态.

我只想获得散列列表中每个键的最高值

例如:

[{1=>19.4}, {1=>12.4}, {2=>29.4}, {3=>12.4}, {2=>39.4}, {2=>59.4}]
Run Code Online (Sandbox Code Playgroud)

结果

[{1=>19.4}, {3=>12.4}, {2=>59.4}]
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 5

我会这样做:

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}]
Run Code Online (Sandbox Code Playgroud)