ruby中Hash可以提供一个默认值,我们可以使用new(object)和default=的这两种方式来设置ruby的默认值。但是有另外一种情况没有提到过,但是也能够修改默认值的方式。
代码如下:
class Kiwi def initialize(val) @val = val end def increase @val += 1 end end hash = Hash.new(Kiwi.new(0)) hash[:x] #=> <Kiwi:0x0000000099bfb0 @val=0> hash[:y].increase hash[:x] #=> <Kiwi:0x0000000099bfb0 @val=1>
可以看出,当第一次调用hash[:x]的时候,因为:x不存在,返回的是默认值为1的Kiwi。但是当我们调用了hash[:y]的时候,因为:y也不存在,所以hash[:y]得到的也是default,但需要注意的是,default不是一个值对象,当我们调用hash[:y].increase的时候,相当于调用了deafult.increase。所以当再次调用hash[:x]的时候,得到的deafult的对象仍然是原来的对象(0x0000000099bfb0),但是@val已经由0变成1。
叫做小陷阱的原因是,如果没有对某个缺失的key赋值,那么永远得到的都是default对象,而如果对这个返回的deafult对象进行操作,将会下一次返回default对象的值的预期。