Building a Histogram : Enumerable « Collections « Ruby






Building a Histogram

module Enumerable
  def to_histogram
    inject(Hash.new(0)) { |h, x| h[x] += 1; h}
  end
end

p [1, 2, 2, 2, 3, 3].to_histogram
# => {1=>1, 2=>3, 3=>2}

p ["a", "b", nil, "c", "b", nil, "a"].to_histogram
# => {"a"=>2, "b"=>2, "c"=>1, nil=>2}

 








Related examples in the same category

1.get Enumerable involved
2.Sorting an Array by Frequency of Appearance
3.Add cartesian to Enumerable
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