On 7/28/06, Sy Ali [email protected] wrote:
d = { 2 => c[1], }
c.merge!(d)
however, I don’t like the way my code looks… I want to be able to
specify the duplication within the hash generation.
Is this possible?
Hmm I am not completely sure what you want achieve.
In the following implementations there are two possible Approaches, the
class YourHash
implements domaindependent key duplication. Iow YourHash is a mapping
from
one Domain to another and both are distinct, thus if the mapping value
is in
the mapped Domain it is just replaced by the mapping value. Ahem that
does
not read well.
I mean:
Keys and values are distinct and thus if a value is already a key it is
replaced by its value.
The second approach is to monkeypatch Hash to add a duplicate method,
allowing you
to define as many “synonyms” or “aliases” for one key.
Hope that helps
Robert
------------------------------------------------- 8<
521/21 > cat hash.rb && ./hash.rb
#!/usr/bin/env ruby
class YourHash < Hash
def []=(key, value)
if has_key?( value ) then
super(key, self[value])
else
super(key, value)
end
end
end
class Hash
def duplicate(key, *tokeys)
value = self[key]
tokeys.each do
|new_key|
self[new_key] = value
end
end
end
h = YourHash.new
h[:a]=1
h[:b]=:a
p h
h = Hash.new
h[:a]=1
h.duplicate( :a, :b, :c )
p h
--------------> OUTPUT <------------------
{:a=>1, :b=>1}
{:c=>1, :a=>1, :b=>1}
–
Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.