哈希初始化:红宝石哈希初始值设定
# 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]
我得到相应的数组。
你可以链接到“另一个问题”? – 2012-03-02 00:22:07
@Andrew:这看起来跟http://stackoverflow.com/q/9492889/479863一样,答案至少基本相同。 – 2012-03-02 00:26:19
另一个问题是http://stackoverflow.com/questions/613985/common-ruby-idioms – 2012-03-02 00:58:09