【发布时间】:2014-10-31 11:58:22
【问题描述】:
这是我的代码:
def mainFunction
@notes=Hash.new(Array.new)
@notes["First"].push(true)
@notes["First"].push(false)
@notes["First"].push(true)
@notes["Second"].push(true)
output @notes.size.to_s
end
为什么输出是0?它应该是2,因为notes 有两个键,"First" 和"Second"。
【问题讨论】:
-
在您的示例中,没有要推送的键。您必须首先初始化指向像
@notes = {"First" => []}这样的数组的键,然后当您执行@notes["First"].push(true)时,它会起作用。 -
How to assign hash[“a”][“b”]= “c” if hash[“a”] doesn't exist? 也类似,或者至少答案应该有助于解决问题。
-
您的问题类似于this one。您可能希望查看那里的答案以获得更多见解。如果您选择不使用
Hash.new {|h, k| h[k] = []},您可能会考虑是否要使用@notes=Hash.new(Array.new)而不是@notes=Hash.new(Array.new)。对于后者,所有键共享同一个数组;对于后者,每个都有自己的数组。不要忘记选择一个答案(如果您发现有任何帮助)。