From: Robert Dober Date: 2006-07-28T18:33:36+09:00 Subject: Re: Creating hashes with duplicate keys ------=_Part_2719_32939589.1154079199482 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 7/28/06, Sy Ali wrote: > > I want to simplify this hash creation: > g =3D { 1 =3D> "test", 2 =3D> "test", } > > I have a particularly complicated hash that I'm generating. It can > have very large values. > > Right now, I duplicate values with something like this: > > c =3D { 1 =3D> "one", } > d =3D { 2 =3D> 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 i= n 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 []=3D(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 =3D self[key] tokeys.each do |new_key| self[new_key] =3D value end end end h =3D YourHash.new h[:a]=3D1 h[:b]=3D:a p h h =3D Hash.new h[:a]=3D1 h.duplicate( :a, :b, :c ) p h --------------> OUTPUT <------------------ {:a=3D>1, :b=3D>1} {:c=3D>1, :a=3D>1, :b=3D>1} --=20 Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_2719_32939589.1154079199482--