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

2023-12-31

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

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

例如:

[{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}]

我会这样做:

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}]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Ruby 中的哈希列表中提取每个键的更大值 的相关文章

随机推荐