Data Aggregation Methods

Introduction to Data Aggregation Methods

Welcome! Today, we’re exploring data aggregation in Ruby, a key tool in data analysis. Think of it as summarizing a big book into its essential points. Data aggregation helps us condense large sets of data into meaningful insights.

By the end of this lesson, you'll be equipped with a range of methods to aggregate and summarize data effectively in Ruby. Let’s dive in!

Basic Aggregation with Built-in Methods

Consider an array of numbers representing the ages of a group of people:

Ruby
ages = [21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22]

Using Ruby’s built-in methods, we can answer common questions like: How many people are there? What’s their total age? Who’s the youngest? Who’s the oldest?

Ruby’s built-in methods length, sum, min, and max can give us quick answers:

Ruby
num_people = ages.length   # Number of people: 12
total_ages = ages.sum      # Total age: 276
youngest_age = ages.min    # Youngest age: 20
oldest_age = ages.max      # Oldest age: 27

For more specific calculations, such as the average age or the range of ages, we combine multiple methods:

Ruby
# Calculate the average age
average_age = ages.sum.to_f / ages.length # Result: 23.0

# Calculate the range of ages
age_range = ages.max - ages.min # Result: 7

These aggregation methods—whether built-in or combined—are essential for quickly summarizing basic information from a dataset.

Advanced Aggregation with Each Loop

For more detailed analysis, such as finding the mode (the most frequent value), we can use the each method to iterate over the data and count occurrences. This requires us to create a custom solution, since Ruby does not have a direct built-in method for calculating mode.

Here’s how we can find the mode of our ages array:

Ruby
ages = [21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22]

# Create a hash to store age frequencies
frequencies = Hash.new(0)

# Populate the hash with frequencies
ages.each do |age|
  frequencies[age] += 1
end

# Find the age with the highest frequency
mode_age, max_freq = frequencies.max_by { |age, freq| freq }
puts "Max frequency: #{max_freq}" # Max frequency: 4
puts "Mode age: #{mode_age}" # Mode age: 22

In this example, frequencies is a hash that stores each age as a key and its count as the value. Using each, we populate frequencies, and then max_by finds the age with the highest count.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal