What should I do to marshal an hash of arrays?
The following code only prints {}
.
s = Hash.new
s.default = Array.new
s[0] <<
s = Hash.new
s.default = Array.new
s[0] << "Tigger"
s[7] << "Ruth"
s[7] << "Puuh"
This code changes the default 3 times (which is probably what showed up in the dump), but it does not store anything in the hash. Try "puts s[8]", it will return [["Tigger"], ["Ruth"], ["Puuh"]].
A Hash.default_proc will do what you want
s = Hash.new{|hash,key| hash[key]=[] }
But you can't marshall a proc. This will work:
s = Hash.new
s.default = Array.new
s[0] += ["Tigger"]
s[7] += ["Ruth"]
s[7] += ["Puuh"]
This works because []+=["Tigger"] creates a new array. An alternative, creating less arrays:
s = Hash.new
(s[0] ||= []) << "Tigger"
(s[7] ||= []) << "Ruth"
(s[7] ||= []) << "Puuh"
Only creates a new array when the key is absent (nil).