Created
February 20, 2012 22:45
-
-
Save Capncavedan/1872044 to your computer and use it in GitHub Desktop.
Useful additions to Enumerable
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 to_histogram | |
result = Hash.new(0) | |
each { |x| result[x] += 1 } | |
result | |
end | |
def most_popular | |
h = self.to_histogram | |
max_by { |x| h[x] } | |
end | |
def most_popular_n(n) | |
ret = [] | |
h = self.to_histogram | |
n.times do | |
ret << max_by { |x| h[x] } | |
h.delete(ret.last) | |
end | |
ret | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment