Skip to content

Instantly share code, notes, and snippets.

@Capncavedan
Created February 20, 2012 22:45
Show Gist options
  • Save Capncavedan/1872044 to your computer and use it in GitHub Desktop.
Save Capncavedan/1872044 to your computer and use it in GitHub Desktop.
Useful additions to Enumerable
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