Go to content
The Codest
  • About Us
  • Services
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
  • About Us
  • Services
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
2022-07-12
Software Development

Hash: To Use or Not to Use

Krzysztof Buszewicz

Senior Software Engineer

Hash: To Use or Not to Use  - Image

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)
                .with_object({ total: 0, total_age: 0 }) do |row, agg|
                  agg[:total] += 1
                  agg[:total_age] += row['Age'].to_i
                end

total = aggregated[:total]
average_age = aggregated[:total_age].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
  attr_reader :total, :total_age

  def initialize
    @total = 0
    @total_age = 0
  end

  def increment!
    @total += 1
  end

  def increment_age!(age)
    @total_age += age
  end

  def average_age
    total_age.to_f / total
  end
end

And then our loop would look as below:

# people/parser.rb

require 'csv'
require_relative './age_aggregator.rb'

aggregated = CSV.foreach('people.csv', headers: true)
                .with_object(AgeAggregator.new) do |row, agg|
                  agg.increment!
                  agg.increment_age!(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

Software Development

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 where we can use this powerful language. Let me give you some examples.

Pawel Muszynski
Technology news

7 Predictions for the IT Industry in 2023

What trends will dominate the IT industry in 2023? These include the outsourcing of IT professionals, the development of cloud-based tools and platforms, the growing popularity of solutions in the spirit of a composable approach...

Greg Polec
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.

Grzegorz Rozmus
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 and level up your project!

Michal Pawlak
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 to master his managerial skills and become a leader? Find the...

Tomasz Szkaradek

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

About us

We are an agile software development company dedicated to empowering our clients' digital transformation projects and ensuring successful IT project delivery.

    United Kingdom - Headquarters

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

    Poland - Local Tech Hubs

  • Business Link High5ive, Pawia 9, 31-154 Kraków, Poland
  • Brain Embassy, Konstruktorska 11, 02-673 Warsaw, Poland
  • Aleja Grunwaldzka 472B, 80-309 Gdańsk, Poland

    The Codest

  • Home
  • About us
  • Services
  • Case studies
  • Know how
  • Careers

    Services

  • PHP development
  • Java development
  • Python development
  • Ruby on Rails development
  • React Developers
  • Vue Developers
  • TypeScript Developers
  • DevOps
  • QA Engineers

    Resources

  • What are top CTOs and CIOs Challenges? [2022 updated]
  • Facts and Myths about Cooperating with External Software Development Partner
  • From the USA to Europe: Why do American startups decide to relocate to Europe
  • Privacy policy
  • Website terms of use

Copyright © 2022 by The Codest. All rights reserved.

We use cookies on the site for marketing, analytical and statistical purposes. By continuing to use, without changing your privacy settings, our site, you consent to the storage of cookies in your browser. You can always change the cookie settings in your browser. You can find more information in our Privacy Policy.