Last Updated: February 25, 2016
·
2.053K
· jordo37

Count occurrences of uniques in ruby

for any given array arr, where you want to count the occurrences of each unique object in the array,

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

so if you have
arr = [a, b, b, c, c, a, a, d]

this will return
=> [a=>3, b=>2, c=>2, d=>1]