Is there a method in Ruby that takes an array, and counts all unique elements and their occurrences and passes them back a S a hash?
For example
[' A ',' A ',' A ',' A ',' B ',' B ',' C '].Method> {' A ' = 4, ' B ' = 2, ' C ' = 1}
Something like that.
[ ' a ' ' a ' ' A ' ' a ' ' B ' ' B ' ' C ' ]. group_by {| e | e map {| k v | [ k , v length to_h
src= [' A ',' A ',' A ',' A ',' B ',' B ',' C ']Hash[src.group_by{ |x|x}.Map{ |k,v| [k,v.length] }]
counts= Hash.New(0)[' A ',' A ',' A ',' A ',' B ',' B ',' C ']. each{ |name|counts[name] += 1 }
Counts = {"A" =>4, "B" =>2, "C" =>1}
[' A ',' A ',' A ',' A ',' B ',' B ',' C '].Each_with_object(Hash.New(0)) { |L,o|o[L] += 1 }
The easiest readable for me:
src= [' A ',' A ',' A ',' A ',' B ',' B ',' C ']src.group_by(&:to_s).to_a.Map{ |a| [a[0],a[1].Count] }.To_h
Or here are another solution with reduce method:
src.reduce({}) { |b, a| b.merge({a => (b[a] || 0) + 1}) }
Pre
src.reduce(Hash.new(0)) { |b, a| b.merge({a => b[a] + 1}) }
Ruby:count unique elements and their occurences in an array