The tally
method has been added to Enumerable in Ruby 2.7
It's a simple little method and as the name suggests, it tallys things for us! It affords us a much simpler way to group items and count their occurrence.
We could always count the size of an array.
fruit_bowl = ["apple", "pear", "pear", "banana", "apple"]
fruit_bowl.count
=> 4
We could count how many of each item an array contained.
fruit_bowl.each.count("apple")
=> 2
Now we can easily take stock of our array items with tally
which will return us a list of items with their respective counts.
fruit_bowl = ["apple", "pear", "pear", "banana", "apple"]
sorted_fruit = fruit_bowl.tally
=> {"apple"=>2, "pear"=>2, "banana"=>1}
sorted_fruit["apple"]
=> 2
Sweet as ππ
Top comments (1)
Love it! I was hacking on a project in Rust the other day and wanted something just like
#tally
! It felt fiddly to write myself and I kept thinking βthis is such a breeze in Rubyβ β€οΈ