gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:15:06 24 4
gpt4 key购买 nike

最近在学习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>'

然后我添加新方法 bar

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 1\n"
"line 2\n"
"line 3\n"

所以,我对 Ruby 中的 IO 感到非常困惑。为什么 foo 中的 puts line 不能正常工作。

最佳答案

有一个puts method in IO IOFile 的父类(super class)。这意味着:

puts line

实际上是 self.puts 而不是 Kernel#puts因为几乎在其他任何地方都可以使用 puts。因此出现“未打开写入”错误消息。

您需要一个显式接收器才能获得与 Kernel#puts 相同的效果; Kernel#puts 等同于 $stdout.puts 所以你想要:

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

您的 p 行 版本工作正常,因为没有 IO#pFile#p 方法,pKernel#p就像其他地方一样。

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

关于Ruby IO - 间接文件输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com