Ruby 初始化:为什么它不执行我的读取指令

发布于 2024-11-27 06:03:25 字数 1007 浏览 7 评论 0原文

这是 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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笔落惊风雨 2024-12-04 06:03:25

初始化方法不应该处理这个问题吗?

它应该。然而,您的方法称为“初始化”。

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

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文