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?
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
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
Thanks,
/ Vahagn
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.