Marshal ruby hash with default proc - remove the default proc?

梦想的初衷 提交于 2019-12-19 05:23:39

问题


I've got a Hash with a default proc that I'd like to Marshal to a file, but the default proc prevents me from doing that.

Rather than writing my own _dump and _load methods, is it possible instead to remove the default proc instead? At the point where I'm Marshalling I'm never going to need the default proc again.


回答1:


Just reset the default:

h.default = nil

More explicitly:

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

In Ruby 2.0, you can also write h.default_proc = nil if you prefer. Available for all Rubies with require 'backports/2.0.0/hash/default_proc'.




回答2:


In case you would want to have a copy without defaults, the simplest way -

Hash[hash_with_defaults]


来源:https://stackoverflow.com/questions/3818623/marshal-ruby-hash-with-default-proc-remove-the-default-proc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!