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

后端 未结 2 768
攒了一身酷
攒了一身酷 2021-01-11 13:55

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

相关标签:
2条回答
  • 2021-01-11 14:11

    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'.

    0 讨论(0)
  • 2021-01-11 14:20

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

    Hash[hash_with_defaults]
    
    0 讨论(0)
提交回复
热议问题