我读取文件的时候遇到了一个问题
class MyFile < File
def foo
self.each_line do | line |
puts line
end
end
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"
非常困惑,求解释。