Marshall serializes hash with block constructor

Here is a snippet of code

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1 # example operation
Marshal.dump(myHash)

I use this often when I try to use it with arbitrary keys, and I did not want to explicitly write something like this

myHash = Hash.new
myHash[5] ||= []  # initialize it first, if needed
myHash[5] << 1    # example operation
Marshal.dump(myHash)

While this is only one line of difference in code, for me, using a block version looks a bit cleaner.

However, there are problems during the serialization process.

in `dump: can't dump hash with default proc (TypeError)

Is there a way to serialize this while continuing to use the block form constructor? Or should I stick to explicitly checking and initializing any values ​​before trying to work with my hash?

I would say no, because there is no real way for a ruby ​​to determine how the hash should automatically generate a value when there is no key without the original proc that was passed.

+3
source
2

, .

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1
myHash.default = nil
Marshal.dump(myHash)

, , , :

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1
Marshal.dump(myHash.tap {|h| h.default = nil })

, . , , .dup:

Marshal.dump(myHash.dup.tap {|h| h.default = nil })

.

+1

http://www.ruby-doc.org/core-2.1.0/Marshal.html :

: , , , , IO , TypeError.

:

class X
  def initialize a
    @a = a
  end
end

Marshal.dump(X.new(1))

= > "\ x04\bo:\x06X\x06:\a @ai\x06"

proc = Proc.new {1}

= > Proc: 0x007ff992716428

Marshal.dump(X.new(Proc))

TypeError: no_dump_data Proc

, default_proc, Proc:

h = Hash.new {1}

= > {}

h.default_proc

= > #Proc: 0x007ff99506ce30 @

, default_proc:

h = Hash.new

= > {}

h.default_proc

= > nil

+1

All Articles