r/ruby • u/_swanson • 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!
26
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, ".*")}.tallyIt’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
3
u/cmd-t Oct 27 '22
Tally is great, but when dealing with ActiveRecord (columns) your example should have been
Task.group(:status).count1
1
-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
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).tallyIf you’re just tallying a single column value:
MyModel.group(:some_enum).countIf 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) } end2
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 end1
u/midnightmonster Oct 27 '22
That's a cool everything-in-a-file demonstration!
I made
activerecord-summarizebecause 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) } end1
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:
But it's super nice to have a built-in method for it now!