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

    Posted on February 24th, 2010 RubyLove No comments

    The array_keys() function in PHP takes an array as it’s argument and returns all the keys in that array (as a numeric array).

    PHP

    $array = array('go' => 'green', 'stop' => 'red');
    var_dump( array_keys($array) );
    /*
    Array (
    	[0] => go
    	[1] => stop
    )
    */

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

    Ruby

    array = { :go => 'green', :stop => 'red' };
    puts array.keys;
    # => [:go, :stop]
  • array_product

    Posted on February 17th, 2010 RubyLove No comments

    The array_product() PHP function returns the product of all values in an array. In other words, it multiplies all values in the array together, and returns the result as a number.

    PHP

    $a = array('1', '2', '3');
    $product_total = array_product($a);
    echo $product_total;
    // => 6

    Ruby

    a = [ "1", "2", "3" ];
    product_total = a.inject {|product, element| product * element }
    puts product_total;
    # => 6
  • array_rand

    Posted on February 16th, 2010 RubyLove No comments

    The array_rand() function in PHP randomly selects one or more elements from an array.

    PHP

    $users = array('john', 'jane', 'tim', 'alex');
    $lucky_winner = array_rand($users);
    echo $lucky_winner;
    // alex

    Ruby

    users = [ 'john', 'jane', 'tim', 'alex' ];
    lucky_winner = users[rand(users.length)];
    puts lucky_winner;
    # => alex