您可能会被 Hash.default 的工作原理误导。
在Marshal.dump 之前,打印数据结构。它是{}。那是因为您将每个字符串连接到 nil 中,而不是连接到空数组中。下面的代码说明并解决了您的问题。
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
返回:
{0=>["Tigger"], 7=>["Ruth", "Puuh"]}
{0=>["Tigger"], 7=>["Ruth", "Puuh"]}
编辑:
我在哈希中插入了很多数据
所以也许一些帮助代码会使插入过程更顺畅:
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