ruby 哈希自动激活(facets) [英] ruby hash autovivification (facets)

查看:41
本文介绍了ruby 哈希自动激活(facets)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在 ruby​​ 中启用哈希自动激活的一个聪明技巧(取自 facets):

Here is a clever trick to enable hash autovivification in ruby (taken from facets):

  # File lib/core/facets/hash/autonew.rb, line 19
  def self.autonew(*args)
    leet = lambda { |hsh, key| hsh[key] = new( &leet ) }
    new(*args,&leet)
  end

虽然它有效(当然),但我真的很沮丧,我无法弄清楚这两个衬垫是如何做的.

Although it works (of course), I find it really frustrating that I can't figure out how this two liner does what it does.

leet 作为默认值.这样就可以访问 h['new_key'] 以某种方式启动它并创建 'new_key' =>{}

leet is put as a default value. So that then just accessing h['new_key'] somehow brings it up and creates 'new_key' => {}

现在,我希望 h['new_key'] 返回默认值对象而不是评估它.也就是说,'new_key' =>{} 不会自动创建.那么 leet 是如何被调用的呢?尤其是两个参数?

Now, I'd expect h['new_key'] returning default value object as opposed to evaluating it. That is, 'new_key' => {} is not automatically created. So how does leet actually get called? Especially with two parameters?

推荐答案

标准 Hash 的新方法 接受一个块.在尝试访问哈希中不存在的键时调用此块.该块传递哈希本身和请求的键(两个参数),并应返回应为请求的键返回的值.

The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.

您会注意到 leet lambda 做了两件事.它返回一个新的哈希值,leet 本身作为处理默认值的块.这是允许 autonew 为任意深度的哈希工作的行为.它还将此新哈希分配给 hsh[key],以便下次请求相同的密钥时,您将获得现有哈希而不是正在创建的新哈希.

You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.

这篇关于ruby 哈希自动激活(facets)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆