Skip to content

Instantly share code, notes, and snippets.

@louis-wu
Created April 20, 2010 04:51
Show Gist options
  • Save louis-wu/372047 to your computer and use it in GitHub Desktop.
Save louis-wu/372047 to your computer and use it in GitHub Desktop.
stock_stats
#---
# Our job is to take all the CSV files and work out how many of each title we have,
# as well as the total list price of the books in stock.
# CSV files looks something like this:
# "Date", "ISBN", "Amount"
# "20080412", "9781934356104", 39.45
# "20080413", "9781934356166", 45.67
# Excerpted from "Programming Ruby"
#---
class BookInStock
attr_reader :isbn, :price
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
end
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
@books_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
@books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
end
end
# later we'll see how to use inject to sum a collection
def total_value_in_stock
sum = 0.0
@books_in_stock.each {|book| sum += book.price}
sum
end
def number_of_each_isbn
# ...
end
end
require_relative 'csv_reader'
reader = CsvReader.new
ARGV.each do |csv_file_name|
STDERR.puts "Processing #{csv_file_name}"
reader.read_in_csv_data(csv_file_name)
end
puts "Total value = #{reader.total_value_in_stock}"
@louis-wu
Copy link
Author

Let’s give ourselves a simple problem to solve. Let’s say that we’re running a secondhand bookstore. Every week, we do stock control. A gang of clerks uses portable bar-code scanners to record every book on our shelves. Each scanner generates a simple comma-separated value (CSV) file containing one row for each book scanned. The row contains (among other things) the book’s ISBN and price. An extract from one of these files looks something like this:

"Date", "ISBN", "Amount"

"20080412", "9781934356104", 39.45

"20080413", "9781934356166", 45.67

Our job is to take all the CSV files and work out how many of each title we have, as well as the total list price of the books in stock.

Whenever you’re designing OO systems, a good first step is to identify the things you’re dealing with. Typically each type of thing becomes a class in your final program, and the things themselves are instances of these classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment