Kürzlich habe ich Ruby gelernt. Ich habe ein Problem, während ich eine Unterklasse von Datei schreibe.Ruby IO - Datei Eingabe/Ausgabe indirekt
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
Ergebnis:
line 1
line 2
line 3
Wenn ich ausgegeben werden soll durch den Aufruf einer Methode:
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
Ergebnis:
/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>'
Dann füge ich neue Methode 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
Ergebnis:
"line 1\n"
"line 2\n"
"line 3\n"
Also, ich bin so verwirrt über IO in Ruby.Why puts line
in foo
kann auch nicht funktionieren.