2010-08-11 92 views
0

嗯,我想代碼大聲疾呼本身:)紅寶石誤差CSV和<<

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

當運行我得到:

# +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>' 

搞什麼名堂我做錯了什麼?

回答

5
'@books_in_stock' != '@book_in_stock' # ! 

(錯別字)

0

你必須在初始化函數一個錯字(@book_in_store insteadn的@books_in_store)。是嗎?

順便說,價格的總和可與inject在一行中完成

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

如果您用ruby -w的命令,它會打開警告,並解釋將解釋了什麼錯誤:

$ 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>'