Created
December 18, 2019 10:05
-
-
Save junegunn/e4097ec8acaf0a2a6b6ce062ab5f08ed to your computer and use it in GitHub Desktop.
Ruby: Array of Hashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = [{ a: 1, b: 9 }, { a: 1, b: 8 }, | |
{ a: 2, b: 7 }, { a: 2, b: 6 }] | |
data.group_by { |h| h[:a] }.transform_values { |xs| xs.max_by { |x| x[:b] } } | |
def key(k) | |
proc { |hash| hash[k] } | |
end | |
data.group_by(&key(:a)).transform_values { |xs| xs.max_by(&key(:b)) } | |
class Array | |
def to_proc | |
proc { |hash| hash[first] } | |
end | |
end | |
data.group_by(&[:a]).transform_values { |xs| xs.max_by(&[:b]) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🤷♂️ 🤷♀️