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