Last active
March 21, 2017 19:32
-
-
Save geeksam/6afc9f99f09d810429a471a9466089dd to your computer and use it in GitHub Desktop.
Enumerable#counts_by
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
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