[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Hash with default_proc and Marshal

benjohn

7/13/2005 11:10:00 AM


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

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.

My solution has been to advoid default_proc, and instead create a Hash sub class:

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

I can then sub class MarshalableHash, implement defaultValueProc, and walk 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 suggestions
for a better approach.

Cheers,
Benjohn





1 Answer

Paul Brannan

7/14/2005 4:07:00 PM

0

On Wed, Jul 13, 2005 at 08:10:01PM +0900, benjohn@fysh.org wrote:
> 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