Ruby 2.7 Enumerable#tally
Have you ever wanted to get back a count of how often objects showed up within an array? If so, you've likely written (or copy-pasta'd) some variation of the code below:
list = %w(red red red blue blue fish blue blue)
list.each_with_object(Hash.new(0)) { |v, h| h[v] += 1 } # => {"red"=>3, "blue"=>4, "fish"=>1}
list.each_with_object({}) { |v, h| h[v] ? h[v] += 1 : h[v] = 1 } # => {"red"=>3, "blue"=>4, "fish"=>1}
list.group_by { |v| v }.map { |k, v| [k, v.size] }.to_h # => {"red"=>3, "blue"=>4, "fish"=>1}
Lucky for us, Ruby 2.7 introduces a new convenience method in Enumerable#tally
, so our above code reduces to:
list = %w(red red red blue blue fish blue blue)
list.tally # => {"red"=>3, "blue"=>4, "fish"=>1}
Huzzah!
You can read the feature discussion here!
Tweet