加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby哈希初始化器

发布时间:2020-12-17 03:53:42 所属栏目:百科 来源:网络整理
导读:哈希初始值设定项: # thisanimals = Hash.new { [] }animals[:dogs] :Scoobyanimals[:dogs] :Scrappyanimals[:dogs] :DynoMuttanimals[:squirrels] :Rocketanimals[:squirrels] :Secretanimals #= {}# is not the same as thisanimals = Hash.new { |_anima
哈希初始值设定项:

# 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]

我得到了合适的数组.

解决方法

第一种形式指定返回未找到的键的默认值的块.这意味着当你调用动物[:dogs]时,没有:狗键入哈希,所以你的块被调用,动物[:dogs]评估你的块的结果,即[].然后会发生什么<< :Scooby追加:Scooby到那个空列表,然后很高兴丢弃. 第二种形式指定了当请求密钥并且未找到密钥时,作为参数接收散列本身和尚未找到的密钥的块.它是第一个构造函数的稍微强大的版本.不同之处在于您的块所做的事情.在第二种形式中,您修改散列以将[]与尚未找到的键相关联.所以现在它存储在哈希中并且<< :Scooby将存储:Scooby那里.进一步调用:dog不会触发块,因为now:dog存在于hash中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读