Sorting an Array by Frequency of Appearance : Enumerable « Collections « Ruby






Sorting an Array by Frequency of Appearance


module Enumerable
  def sort_by_frequency
    histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}
    sort_by { |x| [histogram[x], x] }
  end
end

p [1,2,3,4,1,2,4,8,1,4,9,16].sort_by_frequency

 








Related examples in the same category

1.get Enumerable involved
2.Add cartesian to Enumerable
3.Building a Histogram
4.Call each a number of times
5.randomly each
6.Writing Block Methods that Classify or Collect
7.Implementing Enumerable - Write One Method, Get 22 Free
8.Enumerable.instance_methods.sort
9.Sort on two arrays