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
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