Ruby 2.7 — Enumerable#tally

The Short Version

[1, 1, 2].tally
# => { 1 => 2, 2 => 1 }
[1, 1, 2].map(&:even?).tally
# => { false => 2, true => 1 }

Examples

[1, 2, 2, 3].tally
# => { 1 => 1, 2 => 2, 3 => 1 }
%w(foo foo bar foo baz foo).tally
=> {"foo"=>4, "bar"=>1, "baz"=>1}
%w(foo foo bar foo baz foo).map { |s| s[0] }.tally
=> {“f” => 4, “b” => 2}
%w(foo foo bar foo baz foo).tally_by { |s| s[0] }
=> {“f” => 4, “b” => 2}

Why Use It?

list.group_by { |v| v.something }.transform_values(&:size)list.group_by { |v| v.something }.map { |k, vs| [k, vs.size] }.to_hlist.group_by { |v| v.something }.to_h { |k, vs| [k, vs.size] }list.each_with_object(Hash.new(0)) { |v, h| h[v.something] += 1 }

Vanilla Ruby Equivalent

module Enumerable
def tally_by(&function)
function ||= -> v { v }

each_with_object(Hash.new(0)) do |value, hash|
hash[function.call(value)] += 1
end
end

def tally
tally_by(&:itself)
end
end

The Source Code

Tally?

Wrapping Up

--

--

--

Find new posts on dev.to: https://dev.to/baweaver

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DevOps in Salesforce: Considerations for your deployments

The Best Vendor Management Software of 2021

Learning Python: Printing Floyd’s Triangle with a for Loop- How, and Most importantly, Why?

Kotlin for Interviews — Cheatsheet

Leetcode — 861. Score After Flipping Matrix

Convert Any PDF In To Audio With Python

Delta Investment Tracker — Development Update #4

Elastic Search for Hadoop Cluster (Elastic Stack)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brandon Weaver

Brandon Weaver

Find new posts on dev.to: https://dev.to/baweaver

More from Medium

“Hello, World” in Ruby

Passing a Nested Array of Objects to a Controller to Update Associated Records in Rails

ActiveRecord in Ruby simplified

A Ruby on Rails Guide to Helper Methods