I recently studied Ruby.I hit the problem while I am writing a subclass of the 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
result:
line 1 line 2 line 3
If I want to output by calling the method:
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
Result:
/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>'
Then I add a new bar method
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
Result:
"line 1\n" "line 2\n" "line 3\n"
So, I am so confused about IO in Ruby. Why puts line in foo may not work well.
source share