加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby IO – 间接文件输入/输出

发布时间:2020-12-17 03:24:36 所属栏目:百科 来源:网络整理
导读:最近我一直在学习 Ruby.我在编写File的子类时遇到了问题. class MyFile Fileendfile_path = "text_file"file = MyFile.open(file_path) do | file | file.each_line do | line | puts line end file.closeend 结果: line 1line 2line 3 如果我想通过调用方
最近我一直在学习 Ruby.我在编写File的子类时遇到了问题.

class MyFile < File

end

file_path = "text_file"

file = MyFile.open(file_path) do | file |
    file.each_line do | line |
        puts line
    end
    file.close
end

结果:

line 1
line 2
line 3

如果我想通过调用方法来输出:

class MyFile < File
    def foo
        self.each_line do | line |
            puts line
        end
    end
end

file_path = "text_file"

my_file = MyFile.open(file_path) do | file |
    file.foo
    file.close
end

结果:

/Users/veightz/Developer/RubyCode/io_error.rb:4:in `write': not opened for writing (IOError)
    from /Users/veightz/Developer/RubyCode/io_error.rb:4:in `puts'
    from /Users/veightz/Developer/RubyCode/io_error.rb:4:in `block in foo'
    from /Users/veightz/Developer/RubyCode/io_error.rb:3:in `each_line'
    from /Users/veightz/Developer/RubyCode/io_error.rb:3:in `foo'
    from /Users/veightz/Developer/RubyCode/io_error.rb:20:in `block in <main>'
    from /Users/veightz/Developer/RubyCode/io_error.rb:19:in `open'
    from /Users/veightz/Developer/RubyCode/io_error.rb:19:in `<main>'

然后我添加新的方法栏

class MyFile < File
    def foo
        self.each_line do | line |
            puts line
        end
    end

    def bar
        self.each_line do | line |
            p line
        end
    end
end

my_file = MyFile.open(file_path) do | file |
    file.bar
    file.close
end

结果:

"line 1n"
"line 2n"
"line 3n"

所以,我对Ruby中的IO很困惑.为什么在foo中放入行不能很好地工作.

解决方法

有一个 puts method in IO和IO是File的超类.这意味着:

puts line

实际上是self.puts而不是Kernel#puts,因为它几乎是你使用put的其他地方.因此,“未打开写入”错误消息.

你需要一个明确的接收器来获得与Kernel#puts相同的效果;内核#puts相当于$stdout.puts所以你想要:

file.each_line do | line |
  $stdout.puts line
end

你的p行版本工作正常,因为没有IO#p或File #p方法,p就像Kernel#p一样,就像它在其他任何地方一样.

请记住,我们在Ruby中没有其他语言具有全局功能的方式.像函数一样使用的方法几乎总是Kernel中的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读