From: Charles Hixson Date: 2001-03-16T12:51:35+09:00 Subject: [ruby-talk:12710] Re: (long) Re: hash.invert loses data if equal values exist - is this the right behaviour? On Tuesday 06 March 2001 22:36, you wrote: > Hi, > > In message "[ruby-talk:12179] Re: (long) Re: hash.invert loses data if > equal values exist - is this the right behaviour?" > > on 01/03/07, Dave Thomas writes: > >To be fair, the example does show it: > > > > dave[14:58:19] ri invert > > ---------------------------------------------------------------------- > > hsh.invert -> aHash > > ---------------------------------------------------------------------- > > Returns a new hash created by using hsh's values as keys, and the > > keys as values. > > > > h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } > > h.invert #=> {200=>"d", 300=>"y", 0=>"a", 100=>"n"} > > > > > >Should we make it more explicit? > > I hope so. Could you add some explicit notices like the below? > > ---------------------------------------------------------------------- > hsh.invert -> aHash > ---------------------------------------------------------------------- > Returns a new hash created by using hsh's values as keys, and the > keys as values. Note that the result is uncertain if equvalent > hsh's values are associated to different keys. > > h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } > h.invert #=> {200=>"d", 300=>"y", 0=>"a", 100=>"n"} > > Thanks, > > -- Gotoken What you want to return is a bag, not a set. So the general inverse of a hash would have the second element be a list of values: h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "e"=>200, "a" => 0, "k"=>100} h.invert #=> {200=>["d", "e"], 300=>["y"], 0=>["a"], 100=>["n", "k"]}