Skip to content

Instantly share code, notes, and snippets.

@budu
Created April 25, 2018 22:36
Show Gist options
  • Save budu/30fb0ed13ccb041a5d2dbe4679a4333a to your computer and use it in GitHub Desktop.
Save budu/30fb0ed13ccb041a5d2dbe4679a4333a to your computer and use it in GitHub Desktop.
Cute way to get frequency of items in an enumerable with some bonus methods on the resulting hash.
Enumerable.module_eval do
def frequency
Hash.new(0).tap do |h|
each { |v| h[v] += 1 }
h.define_singleton_method(:highest) { sort_by(&:last).last.first }
h.define_singleton_method(:lowest) { sort_by(&:last).first.first }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment