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.