Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 134 ยท Projects

Project: Inventory and Reports

Build an inventory and reporting tool in Ruby: import CSV from a string, validate rows with Data, group and sort with hashes, and print aligned tables.

Almost every business program ends up doing the same three things: read some tabular data, answer questions about it, and print a report people can read. This project does exactly that for a small shop. We import a stock list in CSV format, turn each row into an object, group and total the numbers with Ruby's hash and enumerable tools, and print aligned tables.

Along the way you will practice hashes, grouping and counting, sorting, Data, CSV and string formatting. The data lives inside the program (in a heredoc), because files created by a program in this sandbox vanish after the run. In a real project you would pass File.read("stock.csv") to the very same code.

csv is a bundled gem since Ruby 3.4, not part of the default library any more. It is installed with Ruby and require "csv" works here, but a real project that uses Bundler needs the line gem "csv" in its Gemfile, otherwise it fails with a LoadError on newer Ruby versions.

Step 1: read CSV into hashes

CSV (comma-separated values) is plain text, one record per line. With headers: true the first line becomes the column names, and header_converters: :symbol turns them into symbols such as :price. The converters: :numeric option converts fields that look like numbers into Integer or Float.

Ruby Step 1: parse CSV text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

CSV.parse returns a CSV::Table, which behaves like an array of CSV::Row objects; row.to_h gives a plain hash. Look at the third data line: "Marker, black" contains a comma, so the CSV format wraps it in double quotes, and the parser keeps it as one field. Splitting lines on "," yourself would break here, which is the main reason to use a real CSV parser.

Prices arrived as Float and quantities as Integer thanks to the converters. A word of caution: floating point numbers are fine for a demo report, but money in a real shop should be integer cents or BigDecimal, as discussed in Numbers.

Step 2: turn rows into objects, and reject bad data

Hashes are flexible, but a typo in a key (:prise) silently returns nil. An immutable Data class gives each row a fixed shape, computed values and a clear failure when something is missing.

Real files contain mistakes, so the importer must decide what to do with a bad row. Stopping at the first problem is annoying for the user; ignoring problems silently is dangerous. A good compromise is to collect the problems, keep the good rows and report both.

Ruby Step 2: Item objects with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each.with_index(2) numbers the rows from 2, because line 1 of the file is the header; the messages then match what a user sees in their spreadsheet. Item.new(**data) expands the row hash into keyword arguments. Note the safety net at the end: Data refuses to build an object with missing fields, so a bad hash can never become a half-filled Item. The value method is a derived value; computing it on demand means it can never get out of step with price and qty.

When the file itself is broken

Row validation covers wrong values. A different class of error is wrong format, such as a quote that never closes. The parser raises CSV::MalformedCSVError, and the importer should turn that into one clear message rather than crash.

Ruby Catching a malformed CSV file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The parser raises CSV::MalformedCSVError with the message Unclosed quoted field in line 2. Left uncaught, the program would stop and print a backtrace through the csv library's own files, which is noise for a user. Rescuing it, as the final program does, lets you print one clear message and exit.

Step 3: grouping, totals and ranking

Now for the questions the shop owner asks: which category holds the most stock value? What is nearly out of stock? What are the top sellers by value? Each is a short chain of enumerable methods. Here we write the data directly as Item objects so the focus stays on the questions.

Ruby Step 3: group_by, sum, tally and sort_by

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is the core of the project; it pays to read each result slowly. group_by returns a hash from category to the list of items. transform_values keeps the keys and replaces each list by its total. max_by takes a block and returns the pair with the biggest number, which we unpack into two variables. tally counts how often each value appears. For sorting by several criteria at once, return an array from sort_by: Ruby compares arrays element by element, so items are sorted by category first and by name within a category. For descending order of numbers, negate the sort key.

Look at the totals: 198.10000000000002 is the usual floating point noise, another reason to use integer cents in real code. Because hashes remember insertion order in Ruby, by_category.keys comes out in the order the categories first appear in the list. That is guaranteed, so you can rely on it in reports.

Step 4: printing aligned tables

A report in a ragged format is hard to read. Two tools make columns line up: ljust and rjust pad strings to a width, and format (alias sprintf) fills a pattern such as %-10s %8.2f. In a format pattern, %-10s is a string padded on the right to 10 characters, %5d is an integer in a field of 5, and %8.2f is a float with two decimals in a field of 8.

Ruby Step 4: a table printer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The helper measures every column (header and cells), pads text to the left and numbers to the right, and joins the cells with a separator. Because the width comes from the data, the table adapts when a long name such as Marker, black shows up. Note that format("%.2f", ...) returns a string, so those prices are left-aligned by our rule that only Numeric cells are right-aligned; passing numbers and formatting them in the helper would be the next improvement.

Step 5: the complete program

Finally we wrap everything in an Inventory class and drive it with scripted commands, as an interactive program would be: report prints the full table with totals per category, low N lists items with fewer than N units, restock SKU N adds stock, and find TEXT searches names case-insensitively. Errors are collected during import and printed first.

Ruby The complete inventory program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The structure is worth studying. The class method Inventory.from_csv is a factory: it builds the object and fills it. The inventory stores items in a hash keyed by SKU, so restock finds an item in one lookup. Data#with creates a new item with one field changed, which fits the immutable style: instead of editing an item we replace it in the hash. The fetch with a block uses return inside the block to leave the method early for an unknown SKU.

In the command loop, the pattern /\A\d+\z/ => limit matches a string against a regular expression and binds the string to limit, so low 20 is accepted but restock P103 abc is not a restock command and falls to the else branch. Pattern matching has done the validation of the shape of the input for us. Line 6 of the file (the Ruler without a price) was rejected during import and reported as a warning, but the rest of the file was still loaded, which is the behavior we wanted.

Ideas to extend it

  • Save the changed stock back to CSV with CSV.generate, and compare it to the input.
  • Add a sell command that fails with a custom exception when there is not enough stock (see Custom Exceptions).
  • Group by price band with chunk_while, or use each_slice to page a long report.
  • Build the report as an ERB template instead of puts calls.
  • Replace Float prices by integer cents and a Money formatter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use a CSV parser instead of line.split(",")?

    A field such as "Marker, black" is one value. A CSV parser understands quoting and escaping rules.
  2. 2. What does items.group_by(&:category) return?

    group_by builds a hash whose keys are the block results and whose values are arrays of the matching elements. Use tally when you only want counts.
  3. 3. How do you sort items by category first and by name within a category?

    Arrays are compared element by element, so returning an array from sort_by sorts by several keys at once.
  4. 4. What does item.with(qty: 5) do on a Data object?

    Data objects are immutable. with builds a modified copy, so the importer replaces the entry in the hash.
  5. 5. Why does the importer collect problems in an array instead of raising at the first bad row?

    For batch imports a report of every problem is more useful than stopping at the first one. Raise only when continuing would be wrong.

Summary

  • CSV.parse(text, headers: true, header_converters: :symbol, converters: :numeric) turns text into rows; csv is a bundled gem, so real projects list it in the Gemfile.
  • Convert rows into immutable Data objects with computed methods, and validate them while importing; collect problems instead of stopping.
  • group_by, transform_values, sum, tally, max_by, sort_by and partition answer most reporting questions in one line each.
  • Sort by several keys by returning an array from sort_by; negate numbers for a descending order.
  • ljust, rjust and format produce aligned columns; compute the widths from the data.
  • Keep the logic in a class and the printing in small helpers, so the same code works for a file, a string or a test.

Next: Project: A Text Adventure Engine