On 21.08.2008 17:46, Michael Libby wrote:
> On Thu, Aug 21, 2008 at 10:34 AM, Lex Williams <etaern / yahoo.com> wrote:
>> I recently tried to learn to use Marshal with a simple script , but I
>> keep getting the following exception : x.rb:6:in `load': marshal data
>> too short (ArgumentError)
>>
>> This is the script :
>>
>> hsh = {:first => [1,2,3],:second => [4,5,6] }
>>
>> File.open("saved.m","w").puts(Marshal.dump(hsh))
> 
> This line is actually the problem from what I can tell.

To explicitly state it: the issue is caused by not proper closing file 
handles.

> Try instead:
> 
> File.open("saved.m", "w"){|f| f.puts(Marshal.dump(hsh)) }

I'd rather do

File.open("saved.m", "wb"){|f| Marshal.dump(hsh, f) }

>> str = (File.open("saved.m").read)
> 
> This works, but is more readable as.
> 
> str = File.read("saved.m")

Again, rather

str = File.open("saved.m","rb") {|f| Marshal.load(f)}

> When you have a short snippet like this, running the code line-by-line
> in irb is often very helpful, since you can see the return values for
> each statement and quickly inspect your variables. At least, that's
> what works for me.

Like

irb(main):001:0> File.open("x","wb"){|f| Marshal.dump({1=>2},f)}
=> #<File:x (closed)>
irb(main):002:0> File.open("x","rb"){|f| Marshal.load(f)}
=> {1=>2}
irb(main):003:0>

Kind regards

	robert