Skip to content

Instantly share code, notes, and snippets.

@aarti
Created May 2, 2014 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/a251dc45301e26fc7836 to your computer and use it in GitHub Desktop.
Save aarti/a251dc45301e26fc7836 to your computer and use it in GitHub Desktop.
How can I extract the bigger value for each key in a list of hashes in Ruby
Many concepts here to revisit, so saving in gist.
http://stackoverflow.com/questions/21712814/how-can-i-extract-the-bigger-value-for-each-key-in-a-list-of-hashes-in-ruby/21729254?noredirect=1#comment32860522_21729254
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}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment