Ruby 初始化:为什么它不执行我的读取指令
这是 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该。然而,您的方法称为“初始化”。
另外:对于 CSV,请使用现有的 CSV 库,并尝试使用 File.open 而不是 File.new(这显示了您用于打开文件的模式)。
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).