小编Jas*_* Yu的帖子

Ruby哈希初始化器

哈希初始值设定项:

# 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]}
Run Code Online (Sandbox Code Playgroud)

我看到有人在另一个问题上发布这些内容,但我不明白为什么动物在第一种情况下显得空白.如果我输入

animals[:dogs]
Run Code Online (Sandbox Code Playgroud)

我得到了合适的数组.

ruby hash autovivification

4
推荐指数
1
解决办法
579
查看次数

标签 统计

autovivification ×1

hash ×1

ruby ×1