You might be misled about how Hash.default
works.
Before you Marshal.dump
, print the data structure. It is {}
. That's because you are concatenating each string into nil, not into an empty array. The code below illustrates and solves your problem.
s = Hash.new
s.default = Array.new
s[0] = []
s[0] << "Tigger"
s[7] = []
s[7] << "Ruth"
s[7] << "Puuh"
p s
data = Marshal.dump(s)
ls = Marshal.restore( data )
p ls
Returns:
{0=>["Tigger"], 7=>["Ruth", "Puuh"]}
{0=>["Tigger"], 7=>["Ruth", "Puuh"]}
EDIT:
I insert a lot of data into the hash
So maybe some helper code would make the insertion process smoother:
def append_to_hash(hash, position, obj)
hash[position] = [] unless hash[position]
hash[position] << obj
end
s = Hash.new
append_to_hash(s, 0, "Tigger")
append_to_hash(s, 7, "Ruth")
append_to_hash(s, 7, "Puuh")
s.default = Array.new // this is only for reading
p s
data = Marshal.dump(s)
ls = Marshal.restore( data )
p ls