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]
Written by Jordan
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#