Getting Hash keys exchanged with values (PHP’s array_flip)


In PHP there is a nifty function that exchanges Hash keys with values: array_flip.

You can have it in Ruby easily too:

hash = {:a => 1, :b => 2, :c => 3}
> pp hash.to_a
[[:c, 3], [:a, 1], [:b, 2]]
>  pp Hash[*hash.to_a.flatten.reverse]
{1=>:a, 2=>:b, 3=>:c}

You can define it as a method of Hash:

class Hash
  def flip
     self.class[*self.to_a.flatten.reverse]
  end
end

>  pp {:a => 1, :b => 2, :c => 3}.flip
{1=>:a, 2=>:b, 3=>:c}

Beware this only works on simple scalar hashes. Check out this proposal for better way.

  1. #1 by recmundas - May 25th, 2010 at 07:31

    Hash.invert

    does exactly the same…

    PHP hurts your mind

(will not be published)
  1. No trackbacks yet.