2010-09-29 91 views

回答

14

只是重置默认:

h.default = nil 

更明确地说:

def dumpable_hash(h) 
    return h unless h.default_proc 
    copy = h.clone 
    copy.default = nil # clear the default_proc 
    copy 
end 

在Ruby 2.0,你也canh.default_proc = nil如果你喜欢。适用于require 'backports/2.0.0/hash/default_proc'的所有红宝石。

+1

原来'h.default = nil'清除默认PROC - 这就是我需要的。谢谢! – 2010-09-29 04:30:17

+0

也可以转储具有默认值对象的散列,例如'Hash.new(42)'。并不是说我喜欢拥有默认值对象,除非它们是不可变的。 – 2011-06-30 23:19:37

5

如果你想有一个副本,不违约,最简单的方法 -

Hash[hash_with_defaults]