class Klass
def initialize(str) @str = str
end
def sayHello @str
end
end
def marshalKlass
o = Klass.new("hello\n")
print o.sayHello
Marshal.dump(o, File.open("output.txt", "w"))
data = File.open("output.txt") # all fine up until here
obj = Marshal.load(data) # EOFError
print obj.sayHello
end
if __FILE__ == $PROGRAM_NAME
marshalKlass
end
*****************************
The line:
obj = Marshal.load(data)
gives the following error:
Klass.rb:19:in `load': end of file reached (EOFError)
from Klass.rb:19:in `marshalKlass'
from Klass.rb:32
The line:
data = File.open("output.txt") places the cursor at the start of the
file. What's wrong?
Ah! "While not closing a read only file usually does not have dramatic
consequences, not closing a file opened for writing likely has dramatic
consequences."
The working method:
def marshalKlass
o = Klass.new("hello\n")
print o.sayHello
dumped = File.open("output.txt", "w")
Marshal.dump(o, dumped)
dumped.close
data = File.open("output.txt", "r")
obj = Marshal.load(data)
data.close
print obj.sayHello
end
This is better but my point in the blog article was a different one: use the block form of File.open because it is more robust.
Cheers
robert
···
On 05.09.2009 14:35, Vahagn Hayrapetyan wrote:
@Robert:
Ah! "While not closing a read only file usually does not have dramatic consequences, not closing a file opened for writing likely has dramatic consequences."
The working method:
def marshalKlass
o = Klass.new("hello\n")
print o.sayHello
dumped = File.open("output.txt", "w")
Marshal.dump(o, dumped)
dumped.close
data = File.open("output.txt", "r")
obj = Marshal.load(data)
data.close
print obj.sayHello
end
def marshal_class
o = Klass.new("hello")
print o.sayHello, " from original object\n"
File.open("data.txt", "w") do |file|
Marshal.dump(o, file)
end
File.open("data.txt", "r") do |file| @obj = Marshal.load(file)
end
print @obj.sayHello + " from restored object\n"
end