Hash with default_proc and Marshal

B

benjohn

I'm relatively new to Ruby (and loving it so far), so I could have got th=
e wrong
end of the stick here!

I have a hash who's values are hashes. I need the default values in the h=
ashes to
be unique to each key, rather than shared. I can achieve this using Hash'=
s
default_proc, instantiating Hash thus:

Hash.new {|hash,key| hash[key] =3D someFunctionGivingANewValue}

However, I require the Hash to be Marshalable, which it will not be if it=
has a
default_proc.

My solution has been to advoid default_proc, and instead create a Hash su=
b class:

class MarshalableHash < Hash
def [](key)
if(!has_key?(key))
self[key] =3D defultValueProc
end
super
end
end

I can then sub class MarshalableHash, implement defaultValueProc, and wal=
k off in
to the sunset with my requirements fulfilled.

While this works, but I'm not very impressed; I'm sure there ought to be =
a nicer
design. For my own improvement as much as my project's, I would welcome s=
uggestions
for a better approach.

Cheers,
Benjohn
 
P

Paul Brannan

I have a hash who's values are hashes. I need the default values in the hashes to
be unique to each key, rather than shared. I can achieve this using Hash's
default_proc, instantiating Hash thus:

Hash.new {|hash,key| hash[key] = someFunctionGivingANewValue}

However, I require the Hash to be Marshalable, which it will not be if it has a
default_proc.

Ruby cannot dump the object, because it cannot dump the proc. One
solution:

irb(main):001:0> h = Hash.new { }
=> {}
irb(main):002:0> Marshal.dump(h)
TypeError: cannot dump hash with default proc
from (irb):2:in `dump'
from (irb):2
irb(main):003:0> module DefaultValueDump; def _dump(limit); Marshal.dump(Hash[*self.keys.zip(self.values)], limit); end; end
=> nil
irb(main):004:0> h.extend(DefaultValueDump)
=> {}
irb(main):005:0> Marshal.dump(h)
=> "\004\010e:\025DefaultValueDumpu:\tHash\t\004\010{\000"

It should be possible to address this using nodewrap, since with
nodewrap it is possible to dump procs. I may do that in a future
version.

Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,171
Messages
2,570,935
Members
47,472
Latest member
KarissaBor

Latest Threads

Top