Ruby:为什么我们不需要`attr_accessor`?

时间:2013-09-24 17:22:34

标签: ruby csv methods

我刚刚从1.9镐书中看了一个例子,我很困惑为什么以下程序成功运行而不使用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

我们不是通过向它添加新的BookInStock对象来写入csv_reader对象的实例变量吗?

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

test_data.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方法是否与访问方法做同样的工作?

1 个答案:

答案 0 :(得分:3)

attr_accessor创建了两个方法,如果你手工编写它们就会大致如此:

def price
  @price
end

def price=(new_price)
  @price = new_price
end

你永远不会调用任何这些方法,因此无论它们是否存在都无关紧要。