Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created January 15, 2020 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/a0cdf6640f54f15db57dbba0b09c4735 to your computer and use it in GitHub Desktop.
Save havenwood/a0cdf6640f54f15db57dbba0b09c4735 to your computer and use it in GitHub Desktop.
A look at how to tally a collection in Ruby, from Ruby 1.9 to 2.7.
# Ruby 1.9
Hash[collection.group_by { |n| n }.map { |k, v| [k, v.size] }]
# Ruby 2.0 Array#to_h
collection.group_by { |n| n }.map { |k, v| [k, v.size] }.to_h
# Ruby 2.2 Object#itself
collection.group_by(&:itself).map { |k, v| [k, v.size] }.to_h
# Ruby 2.4 Hash#transform_values
collection.group_by(&:itself).transform_values(&:size)
# Ruby 2.7 Enumerable#tally
collection.tally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment