Skip to content

Instantly share code, notes, and snippets.

@junegunn
Created December 18, 2019 10:05
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 junegunn/e4097ec8acaf0a2a6b6ce062ab5f08ed to your computer and use it in GitHub Desktop.
Save junegunn/e4097ec8acaf0a2a6b6ce062ab5f08ed to your computer and use it in GitHub Desktop.
Ruby: Array of Hashes
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]) }
@junegunn
Copy link
Author

🤷‍♂️ 🤷‍♀️

@junegunn
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment