From: Robert Klemme Date: 2009-10-26T23:15:12+09:00 Subject: Re: Hash Reverse ? 2009/10/26 Aldric Giacomoni : > Salai Koko wrote: >> I am preparing for my orals exam in Ruby (my last chance.. , If I fail >> the test, no more possible to study Computer Science related :-) ) >> >> http://codepad.org/foNb9Pd3 >> >> class Hash >>   def hash_revert >>     hash_new = Hash.new >>     self.each {|key,value| >>       if not hash_new.has_key?(key) then hash_new[value] = key end >>     } >>     return hash_new >>   end >> end >> >> h = {2=>"a", 1=> "b", 3 =>"a", 4=> "a", 5 => "b", 6=>"c"} >> p h.hash_revert #--> {"a"=>4, "b"=>1, "c"=>6} >> >> or Should I get this ?? >> # => {"a"=>2, "b"=>1, "c"=>6} >> >> Because HASH is working like "Set" ?? >> >> many thanks in advance, >> salai. > > In Ruby 1.9, hashes keep the order of input. Before Ruby 1.9, the order > is "random" - so it's not guaranteed which will be the first key that > you will see with 'each'. As far as I can see salai does not want to reverse the order of elements but rather the key value relationship. Salai, it really depends on the requirements. Here's another valid variant: class Hash def hash_revert r = Hash.new {|h,k| h[k] = []} each {|k,v| r[v] << k} r end end irb(main):008:0> {2=>"a", 1=> "b", 3 =>"a", 4=> "a", 5 => "b", 6=>"c"}.hash_revert => {"a"=>[2, 3, 4], "b"=>[1, 5], "c"=>[6]} http://codepad.org/XNvwvOxi Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/