Created
January 15, 2020 22:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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