Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • array_flip

    Posted on April 19th, 2010 RubyLove 3 comments

    The array_flip() PHP function changes all the keys in an array into values, and all the values into keys.

    PHP

    $a = array('apple' => 1, 'ibm' => 2, 'sun' => 3);
    $flipped = array_flip($a);
    print_r($flipped);
    /*
    Array (
    	[1] => apple
    	[2] => ibm
    	[3] => sun
    )
    */

    To replicate this functionality in Ruby, we will use a Hash object, since arrays in Ruby don’t use associative key / value pairs.

    Ruby

    hash = { "apple" => 1, "ibm" => 2, "sun" => 3 };
    flipped = hash.invert;
    p flipped;
    # => {1 => "apple", 2 => "ibm", 3 => "sun"}

    In PHP, the array_flip() function will over write any conflicting keys. The Ruby invert() method behaves the same - any keys which are the same as other keys will overwrite the previous one.

     

    3 responses to “array_flip”

    1. in the first row of ruby code a syntax mistake… but good description!

    2. Thanks for pointing out the mistake, I have corrected it :)

    3. This is what you would do if you want to flip a Ruby array into a Ruby hash:

      a = ["apple", "orange", "banana"]
      flipped = {}
      a.each_with_index { |e, i| flipped[e] = i }

      p flipped
      => {”apple”=>0, “orange”=>1, “banana”=>2}

    Leave a reply