我刚刚浏览了 1.9 pickaxe book 中的一个示例,我很困惑为什么以下程序可以成功运行而没有attr_accessor
在csv_reader.rb
文件中使用。
book_in_stock.rb
class BookInStock
attr_accessor :price, :isbn
def initialize(price, isbn)
@price = Float(price)
@isbn = isbn
end
end
我们不是通过向 csv_reader 对象的实例变量追加新的 BookInStock 对象来写入它吗?
csv_reader.rb
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
@book_in_stock = []
end
def read_in_csv_data(csv_file)
CSV.foreach(csv_file, headers: true) do |row|
@book_in_stock << BookInStock.new(row["price"], row["isbn"])
end
end
def total_value_in_stock
sum = 0
@book_in_stock.each {|book| sum += book.price}
sum
end
end
测试数据.csv
"price","isbn"
"44.12",'asdf34r13'
"74.12",'asdf34r13'
"14.12",'asdf34r13'
"42.12",'asdf34r13'
"4774.12",'asdf34r13'
"04.19",'asdf34r13'
程序驱动程序
require_relative 'csv_reader'
reader = CsvReader.new
ARGV.each do |csv_file_name|
STDERR.puts "Processing the thing"
reader.read_in_csv_data(csv_file_name)
end
puts "Total Value = #{reader.total_value_in_stock}"
该方法是否与访问read_in_csv_data
器方法执行相同的工作?