Mastering Data Aggregation and JSON Streams

Introduction

Welcome to our lesson on mastering data aggregation and data streams with JSON formatting in Ruby.

In this lesson, we'll start by building a basic sales records aggregator and then extend its functionality to handle more complex operations, such as filtering, data aggregation, and JSON formatting. By the end of this session, you’ll be able to manage and format data streams efficiently with Ruby.

Starter Task Methods and Their Definitions

To begin, we’ll implement a basic sales record aggregator with essential methods:

  • add_sale(sale_id, amount) — Adds a sale record with a unique identifier sale_id and an amount. If a sale with the same sale_id already exists, it updates the amount.
  • get_sale(sale_id) — Retrieves the sale amount associated with the sale_id. If the sale does not exist, it returns nil.
  • delete_sale(sale_id) — Deletes the sale record with the given sale_id. Returns true if the sale was deleted and false if the sale does not exist.

With these methods in place, let’s proceed to the code.

Starter Task Solution

Here is the complete code for the starter task:

Ruby
class SalesAggregator
  def initialize
    @sales = {}
  end

  def add_sale(sale_id, amount)
    @sales[sale_id] = amount
  end

  def get_sale(sale_id)
    @sales[sale_id]
  end

  def delete_sale(sale_id)
    !!@sales.delete(sale_id)
  end
end

The initialize method sets up an empty hash to store sales records. The add_sale method either adds a new sale or updates the amount if a sale with the same ID already exists. The get_sale method retrieves the amount for a given sale ID, returning nil if the sale does not exist. The delete_sale method removes the sale record for a specified sale ID, returning false if the sale does not exist.

To test these methods, here’s some example usage:

Ruby
# Example Usage
aggregator = SalesAggregator.new

# Add sales
aggregator.add_sale('001', 100.50)
aggregator.add_sale('002', 200.75)

# Get sale
puts aggregator.get_sale('001')  # Output: 100.5

# Delete sale
puts aggregator.delete_sale('002')  # Output: true
puts aggregator.get_sale('002')  # Output: nil

With the basic aggregator working, let’s expand its functionality to handle more advanced operations.

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