Skip to content

Instantly share code, notes, and snippets.

@geeksam
Last active March 21, 2017 19:32
Show Gist options
  • Save geeksam/6afc9f99f09d810429a471a9466089dd to your computer and use it in GitHub Desktop.
Save geeksam/6afc9f99f09d810429a471a9466089dd to your computer and use it in GitHub Desktop.
Enumerable#counts_by
module Enumerable
def counts_by(&property)
group_by(&property) # Group my values by some interesting property
.lazy # (in a potentially more GC-friendly way),
.map {|x,xs| [ x, xs.length ] } # collapsing the sub-lists of values to simple counts...
.sort_by(&:last) # and show them in increasing order of frequency (so that,
# if the list is very long, the high numbers are at the end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment