array_flip

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.

By | 2010-07-05T23:17:47+00:00 April 19th, 2010|Categories: PHP, Ruby|Tags: , , , |3 Comments

About the Author:

3 Comments

  1. bakancs July 5, 2010 at 10:31 pm

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

  2. RubyLove July 5, 2010 at 11:18 pm

    Thanks for pointing out the mistake, I have corrected it 🙂

  3. Jaume Sola July 3, 2011 at 9:33 pm

    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}

Comments are closed.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.