Recently, Ruby 2.7-preview3 is released.
This release has an interesting method - Enumable#tally
. It counts the occurrence of each element.
Before ruby 2.7, we achieve the aim with the following code:
array
.group_by { |v| v }
.map { |k, v| [k, v.size] }
.to_h
array
.group_by { |v| v }
.transform_values(&:size)
array.each_with_object(Hash.new(0)) { |v, h| h[v] += 1 }
In 2.7, we can instead use tally
:
["A", "B", "C", "B", "A"].tally #=> {"A"=>2, "B"=>2, "C"=>1}
FYI: