2011-07-31 21 views
1

這是7周內7種編程語言的Ruby部分的第3天的代碼。我不能輸出任何東西,如果我不在m = RubyCsv.new後寫m.readRuby初始化:爲什麼它不執行我的讀取指令

不應該使用initialize方法嗎?

要測試您可以使用包含

一個簡單的rubycsv.txt文件中的兩個

1,2

這裏是Ruby代碼:

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 

回答

2

不應該初始化方法照顧呢?

它應該。然而你的方法被稱爲「初始化」。

另外:對於CSV使用現有的CSV庫,並嘗試使用File.open而不是File.new(這顯示了用於打開文件的模式)。

+1

哇我覺得真的很愚蠢。謝謝! – stanm87

相關問題