我应该怎么做才能编码数组的散列?
以下代码仅打印 {}
。
s = Hash.new
s.default = Array.new
s[0] << "Tigger"
s[7] << "Ruth"
s[7] << "Puuh"
data = Marshal.dump(s)
ls = Marshal.restore( data )
p ls
如果散列不包含数组,它会被正确恢复。
最佳答案
s = Hash.new
s.default = Array.new
s[0] << "Tigger"
s[7] << "Ruth"
s[7] << "Puuh"
此代码更改默认值 3 次(这可能是在转储中显示的内容),但它不会在散列中存储任何内容。尝试“puts s[8]”,它将返回 [["Tigger"]、["Ruth"]、["Puuh"]]。
Hash.default_proc 会做你想做的事
s = Hash.new{|hash,key| hash[key]=[] }
但是你不能编码一个过程。这将起作用:
s = Hash.new
s.default = Array.new
s[0] += ["Tigger"]
s[7] += ["Ruth"]
s[7] += ["Puuh"]
之所以可行,是因为 []+=["Tigger"] 创建了一个新 数组。 另一种方法是创建更少的数组:
s = Hash.new
(s[0] ||= []) << "Tigger"
(s[7] ||= []) << "Ruth"
(s[7] ||= []) << "Puuh"
仅当键不存在(nil)时才创建一个新数组。
关于ruby - 如何用数组编码哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2552363/