Ruby 中 Hash#default_proc的用法

本文介绍了如何使用Ruby语言构建一个可以进行多维赋值的递归Hash表,并详细解释了其工作原理。通过使用特殊的初始化块,可以在不存在的键被访问时自动创建新的Hash实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果要构建一个多维的hash表

a = {} 
a[1][2] = 2

会出现如下错误:

NoMethodError: undefined method `[]' for 2015-09-02 03:16:21 +0000:Time

错误的原因在于:

a 没有[][]方法,或者说,方法[]=返回的结果不是一个Hash,无法继续进行赋值。

构建方法

deep_hash = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) }; 

这样就建立一个递归的hash.

deep_hash[:a][:b][:c] = "weee!"; 
deep_hash 
# => {:a=>{:b=>{:c=>"weee!"}}}

###原理

new {|hash, key| block } → new_hash

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.

在初始值里面的block有一个特点,会在没有key的时候会执行。如:

h = Hash.new { Time.now}
p h #是空表
a = h[:a] #表示是具体的时间

在上述递归Hash表中,default_proc 就是一个递归的block: { |h,k| h[k] = Hash.new(&h.default_proc) }会不断的产生新Hash,从而实现Hash的递归。

转载于:https://my.oschina.net/greister/blog/500597

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值