【发布时间】:2011-07-31 21:54:25
【问题描述】:
这是 7 周内 7 种编程语言的 Ruby 部分第 3 天的代码。如果我在 m = RubyCsv.new 之后不写 m.read,我将无法输出任何内容
初始化方法不应该解决这个问题吗?
您可以使用一个简单的 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
【问题讨论】:
标签: ruby metaprogramming dsl