Ruby initialize: why doesn't it execute my read instruction
This is code from the day 3 of the Ruby section of 7 programming languages in 7 weeks. I can't get it to output anything if I don't write m.read just after m = RubyCsv.new
Shouldn't the initialize method take care of that ?
To test you can use a simple rubycsv.txt file containing
开发者_运维技巧one, two
1, 2
And here is the ruby code:
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
def read
@csv_contents = []
filename = 'rubycsv.txt'
file = File.new(filename)
@headers = file.gets.chomp.split(', ')
file.each do |row|
@csv_contents << row.chomp.split(', ')
end
end
attr_accessor :headers, :csv_contents
def initalize
read
end
end
end
class RubyCsv
include ActsAsCsv
acts_as_csv
end
m = RubyCsv.new
**m.read** #this shouldn't be necessary according to the book
puts m.headers.inspect
puts m.csv_contents.inspect
Shouldn't the initialize method take care of that ?
It should. Your method however is called "initalize".
Also: for CSV use existing CSV libraries, and try to use File.open instead of File.new (this shows the mode you are using for opening the file).
精彩评论