【发布时间】:2012-03-20 12:54:39
【问题描述】:
哈希初始化器:
# this
animals = Hash.new { [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {}
# is not the same as this
animals = Hash.new { |_animals, type| _animals[type] = [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {:squirrels=>[:Rocket, :Secret], :dogs=>[:Scooby, :Scrappy, :DynoMutt]}
我看到有人在另一个问题上发布了这些,但我不明白为什么动物在第一种情况下显示为空白。如果我输入
animals[:dogs]
我得到了合适的数组。
【问题讨论】:
-
你能链接到“另一个问题”吗?
-
@Andrew:这看起来和stackoverflow.com/q/9492889/479863一样,至少答案基本相同。
标签: ruby hash autovivification