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_idand anamount. If a sale with the samesale_idalready 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 returnsnil. - delete_sale(sale_id) — Deletes the sale record with the given
sale_id. Returnstrueif the sale was deleted andfalseif 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:
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:
With the basic aggregator working, let’s expand its functionality to handle more advanced operations.
