【问题标题】:Ruby initialize: why doesn't it execute my read instructionRuby 初始化:为什么它不执行我的读取指令
【发布时间】:2011-07-31 21:54:25
【问题描述】:

这是 7 周内 7 种编程语言的 Ruby 部分第 3 天的代码。如果我在 m = RubyCsv.new 之后不写 m.read,我将无法输出任何内容

初始化方法不应该解决这个问题吗?

您可以使用一个简单的 ruby​​csv.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


    【解决方案1】:

    初始化方法不应该解决这个问题吗?

    应该的。但是,您的方法称为“初始化”。

    另外:对于 CSV,请使用现有的 CSV 库,并尝试使用 File.open 而不是 File.new(这显示了您用于打开文件的模式)。

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 2011-08-16
      • 1970-01-01
      • 2012-08-23
      • 2011-05-26
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多