tags:

views:

46

answers:

3

Well, I think the code speaks out for itself :)

# book_in_stock.rb

class BookinStock
  attr_reader :isbn, :price

  def initialize(isbn, price)
    @isbn = isbn
    @price = Float(price)
  end
end

# csv_reader.rb

require 'csv'

class CsvReader
  def initialize
    @book_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

# stock_stats.rb

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}"

When running I get:

# +search/pickaxe/csv $ ruby1.9.1 test.rb data.csv 
# [+] Processing data.csv
# test.rb:23:in `block in read_in_csv_data': undefined method `<<' for nil:NilCla
# ss (NoMethodError)
#        from /usr/lib/ruby/1.9.1/csv.rb:1760:in `each'
#        from /usr/lib/ruby/1.9.1/csv.rb:1196:in `block in foreach'
#        from /usr/lib/ruby/1.9.1/csv.rb:1334:in `open'
#        from /usr/lib/ruby/1.9.1/csv.rb:1195:in `foreach'
#        from test.rb:22:in `read_in_csv_data'
#        from test.rb:46:in `block in <main>'
#        from test.rb:44:in `each'
#        from test.rb:44:in `<main>'

What've I done wrong?

+5  A: 
'@books_in_stock' != '@book_in_stock' # !

(typo)

mykhal
A: 

You have a typo in the initialize function (@book_in_store insteadn of @books_in_store). Is that it?

By the way, the sum of the prices can be done with inject in one line

@books_in_stock.inject(0) { |sum, book| sum + book.price }
Chubas
A: 

If you run the command with ruby -w, it'll turn on warnings, and the interpreter will explain what went wrong:

$ ruby -w book_in_stock.rb
book_in_stock.rb:28: warning: instance variable @books_in_stock not initialized
book_in_stock.rb:28:in `total_value_in_stock': undefined method `each' for nil:NilClass (NoMethodError)
        from book_in_stock.rb:47:in `<main>'
Andrew Grimm