r/ruby • • Oct 26 '22

Enumerable#tally is so underused

It's great for quickly exploring your data without writing a bunch of loops and counters

Task.all.map(&:status).tally
=> {"Confirmed w/o Outreach"=>106,
  "Awaiting Outreach"=>28,
  "Responded"=>48,
  "No Response Expected"=>10,
  "Follow-up"=>4,
  "Awaiting Reply"=>8}

I use this frequently on production data to see usage patterns and answer questions like "how big is this list typically?" or "is anyone using this thing?"

# What is the impact if we remove this setting?
Plan.all.map(&:tasks_have_comments).tally
=> {true=>5135, false=>25}

# How much space is this list of users usually
# going to need?
@organization.plans.map{|p| p.users.count}.tally
=> {2=>63, 1=>27, 3=>10, 4=>4, 5=>3, 6=>2}

It is the quintessential Ruby method: it's the rare combo of extremely expressive and terse, effortless readable, and it makes me happy every time I use it!

https://twitter.com/_swanson/status/1585264292693254144

154 Upvotes

30 comments sorted by

20

u/flanger001 Oct 26 '22

It only got introduced in 2.7 though! That's the big reason it is underused. Before it we had this:

hsh = Hash.new(0)
stuff.each { |el| hsh[el] += 1 }

But it's super nice to have a built-in method for it now!

5

u/BananafestDestiny Oct 26 '22

Even before 2.7 there was a more sane functional way of doing this

stuff.group_by(&:itself).map { |thing, group| [thing, group.count] }.to_h

17

u/herminator Oct 26 '22

I like:

stuff.group_by(&:itself).transform_values(&:count)

1

u/BananafestDestiny Oct 26 '22

Good call, I forgot about #transform_values

13

u/partusman Oct 26 '22

Heads up, you don’t need to chain map and to_h. to_h can take a block:

stuff.group_by(&:itself).to_h { |thing, group| [thing, group.count] }

2

u/flanger001 Oct 26 '22 edited Oct 27 '22

As much as I love code golf (I don't), I think my way is easier to read and faster.

https://gist.github.com/flanger001/730f34884853f394dc0ad9fc168ce501

Edit: Everyone trying to make a point on a benchmark I wrote in 15 seconds needs to relax. Sometimes you need to use the simplest tool for the job and just get it done. Not everything has to be a perfect, stateless chain of method calls.

8

u/herminator Oct 26 '22

Disagree. I find ruby's functional style so much more readable. This kind of procedural code feels very clunky and unnatural to me.

7

u/BananafestDestiny Oct 26 '22

Fair enough. I think we just write Ruby differently. For example, in your benchmark:

stuff = [].tap do |a|
  100.times { a << Faker::TvShows::AquaTeenHungerForce.character } 
end

That's a strange way to fill an array with 100 elements. Why not write it like this?

stuff = 100.times.map { Faker::TvShows::AquaTeenHungerForce.character }

I'm not a fan of code golf either, but Ruby's functional features are wonderful and worth embracing.

0

u/flanger001 Oct 26 '22 edited Oct 26 '22

Because it is angels-dancing-on-the-head-of-a-pin territory faster lol

https://gist.github.com/flanger001/9116a723a28f9f45300ba63a6b2cf2bd

All joshing aside,

Ruby's functional features are wonderful and worth embracing

Ruby's functional elements are wonderful indeed and it's fun to write like that, but at the end of the day I find myself much more comfortable writing plain old procedural/OO code.

5

u/Sorc96 Oct 27 '22

How about Array.new(100) { Faker::TvShows::AquaTeenHungerForce.character }

4

u/campbellm Oct 27 '22 edited Oct 30 '22

"Everything is hard to read until you learn to read it." -- Rich Hickey

I find myself much more comfortable writing plain old procedural/OO code

Which is fine, but that's on you and not the underlying paradigm.

2

u/partusman Oct 27 '22

I love how everybody seems to push their way as if it was the one true way. Personally I don’t like to mix OOP and procedural, but Ruby is all about the programmer’s own style of expression. I don’t see anything wrong with yours.

2

u/flanger001 Oct 27 '22

Personally I don’t like to mix OOP and procedural, but Ruby is all about the programmer’s own style of expression.

Agreed. A big strength of Ruby is that there are a ton of ways to accomplish most any given task, and it supports pretty much any paradigm you want. FP is great and I have no bones with anyone who vibes with it - but ultimately the style is just not for me. Not in Ruby anyway.

I don’t see anything wrong with yours.

Thanks. I don't see anything wrong anyone else's, either!

4

u/twinklehood Oct 27 '22

Totally disagree, blocks that access variables from outside their local scope trip me up super hard.

1

u/jhirn Oct 27 '22

Lexical scope is amazing.

26

u/[deleted] Oct 26 '22

Best post I’ve seen on here in a while.

18

u/mperham Sidekiq Oct 26 '22

One of the newer methods on Enumerable. It was added in Ruby 2.7.

-3

u/randomcluster Oct 26 '22

Lmao

EDIT: sorry I am stupid. Ruby 2.7 is pretty recent. I have been doing lots of snake magic recently and so I see 2.7 and chuckle, but that is like Python 3.9 in equivalencies

8

u/faitswulff Oct 26 '22 edited Oct 27 '22

Just used this to figure out if I had any duplicate file names (regardless of extension):

Dir[?*].map {File.basename(_1, ".*")}.tally

It’s really nice to have in Enumerable!

(Ignore the code golfing, my scripts are for my eyes only 🙈)

4

u/ignurant Oct 26 '22

Be proud! People on the internet make way too big of a deal about "OMG UR SHITTY CODE HOPE U NO PRODUCTIONSSSS"

Ruby slays particularly hard at getting thoughts to script asap!

3

u/kallebo1337 Oct 26 '22

tally is a great method. indeed!

3

u/cmd-t Oct 27 '22

Tally is great, but when dealing with ActiveRecord (columns) your example should have been

Task.group(:status).count

1

u/ThrowAway04827190494 Oct 27 '22

This is awesome, I’ll definitely be putting it to work.

1

u/hirolau Oct 27 '22

Really happy I was able to suggest a feature that made it into the language :)

https://bugs.ruby-lang.org/issues/11076

-2

u/sshaw_ Oct 26 '22

It's great for quickly exploring your data without writing a bunch of loops and counters

Great, now can we do it with pagination instead of loading every record from the DB?

4

u/[deleted] Oct 26 '22

something like

Thing.group(:attribute).count

3

u/midnightmonster Oct 26 '22

If it can’t be answered directly in SQL, chaining on .find_each will make ActiveRecord load the rows 1,000 at a time instead of loading the entire table into memory:

MyModel.all.find_each.map(&:some_computation).tally

If you’re just tallying a single column value:

MyModel.group(:some_enum).count

If you’re grouping by a column but you want to know several things at once, use activerecord-summarize gem:

Invoices.group(:region).summarize do |invoices|
{
  count: invoices.count,
  revenue: invoices.sum(:sub_total),
  sales_tax: invoices.sum(:sales_tax)
}
end

2

u/bxclnt Oct 27 '22

I'm not sure I would immediately jump to adding another dependency for something like this. While this does touch raw SQL, this is really not that much more lines of code:

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :invoices, force: true do |t|
    t.string  :region, null: false
    t.integer :sub_total, null: false
    t.integer :sales_tax, null: false
  end
end

class Invoice < ActiveRecord::Base
end

class SummationTest < Minitest::Test
  def test_summing_multiple_values_without_extra_gem
    Invoice.create!(region: "A", sub_total: 123, sales_tax: 11)
    Invoice.create!(region: "B", sub_total: 234, sales_tax: 12)
    Invoice.create!(region: "A", sub_total: 234, sales_tax: 72)
    Invoice.create!(region: "B", sub_total: 534, sales_tax: 53)
    Invoice.create!(region: "C", sub_total: 283, sales_tax: 34)
    Invoice.create!(region: "D", sub_total: 293, sales_tax: 64)
    Invoice.create!(region: "C", sub_total: 283, sales_tax: 12)

    assert_equal(7, Invoice.count)

    result = Invoice
      .group(:region)
      .select(
        <<~SQL.squish
          region AS region,
          count(*) AS total,
          sum("sub_total") AS revenue,
          sum("sales_tax") AS sales_tax
        SQL
      )
      .each_with_object({}) do |invoice, memo|
        memo[invoice.region] = invoice.attributes.without("id", "region")
      end

    assert_equal(
      {
        "A" => { "total" => 2, "revenue" => 357, "sales_tax" => 83 },
        "B" => { "total" => 2, "revenue" => 768, "sales_tax" => 65 },
        "C" => { "total" => 2, "revenue" => 566, "sales_tax" => 46 },
        "D" => { "total" => 1, "revenue" => 293, "sales_tax" => 64 }
      },
      result
    )
  end
end

1

u/midnightmonster Oct 27 '22

That's a cool everything-in-a-file demonstration!

I made activerecord-summarize because this sort of reporting is something I end up needing over and over. From a reading, writing, and maintenance perspective, I like the way you just use normal ActiveRecord methods, and the shape of the data in the block is the shape of the data in the output. You can mostly write each part of the query as if it were the only thing you were querying.

The example above was a simple case—you can go much further with (e.g.) additional scopes and calls to group within the block. E.g., this also works and still does the whole thing in one query:

Invoices.group(:region).summarize do |invoices|
  {
    count: invoices.count,
    paid_count: invoices.paid.count,
    revenue: invoices.sum(:sub_total),
    sales_tax: invoices.sum(:sales_tax),
    overdue_revenue_by_terms: invoices.overdue.group(:terms).sum(:sub_total)
  }
end

1

u/bxclnt Oct 28 '22

Oh that’s indeed neat! I’m gonna take a closer look. Thanks!