Search code examples
ruby

How to group by count in array without using loop


arr = [1,2,1,3,5,2,4]

How can I count the array by group value with sorting? I need the following output:

x[1] = 2  
x[2] = 2  
x[3] = 1  
x[4] = 1  
x[5] = 1

Solution

  • x = arr.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }