csv - Ruby: Why don't we need `attr_accessor`? -
i ran through example 1.9 pickaxe book , i'm confused why following program runs without using attr_accessor
in csv_reader.rb
file.
book_in_stock.rb
class bookinstock attr_accessor :price, :isbn def initialize(price, isbn) @price = float(price) @isbn = isbn end end
aren't writing instance variable of csv_reader object appending new bookinstock objects it?
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) |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'
program driver
require_relative 'csv_reader' reader = csvreader.new argv.each |csv_file_name| stderr.puts "processing thing" reader.read_in_csv_data(csv_file_name) end puts "total value = #{reader.total_value_in_stock}"
is read_in_csv_data
method doing same job accessor method?
attr_accessor
creates 2 methods if write them hand:
def price @price end def price=(new_price) @price = new_price end
you never calling of methods, irrelevant whether exist or not.
Comments
Post a Comment