window.pipedriveLeadboosterConfig = { base: 'leadbooster-chat.pipedrive.com', companyId: 11580370, playbookUuid: '22236db1-6d50-40c4-b48f-8b11262155be', version: 2, } ;(function () { var w = window if (w.LeadBooster) { console.warn('LeadBooster already exists') } else { w.LeadBooster = { q: [], on: function (n, h) { this.q.push({ t: 'o', n: n, h: h }) }, trigger: function (n) { this.q.push({ t: 't', n: n }) }, } } })() Hash: To Use or Not to Use - The Codest
The Codest
  • About us
  • Services
    • Software Development
      • Frontend Development
      • Backend Development
    • Staff Augmentation
      • Frontend Developers
      • Backend Developers
      • Data Engineers
      • Cloud Engineers
      • QA Engineers
      • Other
    • It Advisory
      • Audit & Consulting
  • Industries
    • Fintech & Banking
    • E-commerce
    • Adtech
    • Healthtech
    • Manufacturing
    • Logistics
    • Automotive
    • IOT
  • Value for
    • CEO
    • CTO
    • Delivery Manager
  • Our team
  • Case Studies
  • Know How
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
  • About us
  • Services
    • Software Development
      • Frontend Development
      • Backend Development
    • Staff Augmentation
      • Frontend Developers
      • Backend Developers
      • Data Engineers
      • Cloud Engineers
      • QA Engineers
      • Other
    • It Advisory
      • Audit & Consulting
  • Value for
    • CEO
    • CTO
    • Delivery Manager
  • Our team
  • Case Studies
  • Know How
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
Back arrow GO BACK
2022-07-12
Software Development

Hash: To Use or Not to Use

The Codest

Krzysztof Buszewicz

Senior Software Engineer

Read an article coming from our Ruby Expert and learn why you don’t need to always youse hash.

Introduction

When we want to aggregate some stuff, very often we use #each_with_object or extend the regular loop using #with_object. But in most cases Ruby developers are using a plain hash as the aggregator and maybe it’s fine, but in this article, I’d like to show you that it doesn’t always have to be a hash.

Case

We assume that all the files are placed in one directory (people).

Let’s say we have the following people/people.csv file:

 First Name,Last Name,Age
 John,Doe,24
 Jane,Dee,45
 Josh,Bee,55
 Andrea,Boya,34
 Andrew,Moore,54

We want to find the total of rows and the average age – we could write the following script:

people/parser.rb

require 'csv'

aggregated = CSV.foreach('people.csv', headers: true)
.withobject({ total: 0, totalage: 0 }) do |row, agg|
agg[:total] += 1
agg[:totalage] += row['Age'].toi
end

total = aggregated[:total]
averageage = aggregated[:totalage].to_f / total

puts "Total: #{total}"
puts "Average age: #{average_age}"

And yes, it does the thing but reading such a code is a doubtful pleasure. It feels like a too low level. We can improve it by providing a dedicated aggregator for the loop.

people/age_aggregator.rb

class AgeAggregator
attrreader :total, :totalage

def initialize
@total = 0
@total_age = 0
end

def increment!
@total += 1
end

def incrementage!(age)
@totalage += age
end

def averageage
totalage.to_f / total
end
end

And then our loop would look as below:

people/parser.rb

require 'csv'
requirerelative './ageaggregator.rb'

aggregated = CSV.foreach('people.csv', headers: true)
.withobject(AgeAggregator.new) do |row, agg|
agg.increment!
agg.incrementage!(row['Age'].to_i)
end

puts "Total: #{aggregated.total}"
puts "Average age: #{aggregated.average_age}"

I think it’s much clearer.

Summary

We’ve written more code, but our lower-level details are extracted to the separate class. Now the main script reads much better.

Of course, you can argue that the example is too simple to put so much effort into refactoring, but c’mon – it’s just an example ;). If you had to aggregate more data, such aggregator objects are really the way to rescue.

cooperation banner

Read more:

Pros and cons of Ruby software development

Rails and Other Means of Transport

Rails Development with TMUX, Vim, Fzf + Ripgrep

Related articles

Fintech

5 examples of Ruby’s best usage

Have you ever wondered what we can do with Ruby? Well, the sky is probably the limit, but we are happy to talk about some more or less known cases...

The Codest
Pawel Muszynski Software Engineer
Software Development

Hiring Internal vs. External Developers

Hiring internally or externally? It's an ultimate dilemma! Find out advantages of outsourcing or building an in-house team in the following article.

The Codest
Grzegorz Rozmus Java Unit Leader
Software Development

The Codest’s Success Story: From Ruby Dev to Masterclass Leader

Meet Tomasz Szkaradek - Head of People Operations at The Codest. Discover Tomek’s career journey from a Ruby Manager to a member of the core group. How did he manage...

The Codest
Tomasz Szkaradek Development Architect
Software Development

Learn More about Ruby on Rails with Pub/Sub

Pub/Sub can bring many benefits to the project – it can make the code clean, decouple services and make them easily scalable. Learn more about Pub/Sub in the following article...

The Codest
Michal Pawlak Senior Ruby Developer

Subscribe to our knowledge base and stay up to date on the expertise from the IT sector.

    About us

    The Codest – International software development company with tech hubs in Poland.

    United Kingdom - Headquarters

    • Office 303B, 182-184 High Street North E6 2JA
      London, England

    Poland - Local Tech Hubs

    • Fabryczna Office Park, Aleja
      Pokoju 18, 31-564 Kraków
    • Brain Embassy, Konstruktorska
      11, 02-673 Warsaw, Poland

      The Codest

    • Home
    • About us
    • Services
    • Case Studies
    • Know How
    • Careers
    • Dictionary

      Services

    • It Advisory
    • Software Development
    • Backend Development
    • Frontend Development
    • Staff Augmentation
    • Backend Developers
    • Cloud Engineers
    • Data Engineers
    • Other
    • QA Engineers

      Resources

    • Facts and Myths about Cooperating with External Software Development Partner
    • From the USA to Europe: Why do American startups decide to relocate to Europe
    • Tech Offshore Development Hubs Comparison: Tech Offshore Europe (Poland), ASEAN (Philippines), Eurasia (Turkey)
    • What are the top CTOs and CIOs Challenges?
    • The Codest
    • The Codest
    • The Codest
    • Privacy policy
    • Website terms of use

    Copyright © 2025 by The Codest. All rights reserved.

    en_USEnglish
    de_DEGerman sv_SESwedish da_DKDanish nb_NONorwegian fiFinnish fr_FRFrench pl_PLPolish arArabic it_ITItalian jaJapanese ko_KRKorean es_ESSpanish nl_NLDutch etEstonian elGreek en_USEnglish