From: Paul Brannan Date: 2005-07-15T01:07:05+09:00 Subject: Re: Hash with default_proc and Marshal 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