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

    Posted on February 16th, 2010 RubyLove 1 comment

    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
  • shuffle

    Posted on May 26th, 2009 RubyLove No comments

    Randomizes the order of the elements in an array.

    PHP

    $a = array('a', 'b', 'c', 'd');
    shuffle($a);
    print_r($a);
    /*
    Array (
    	[0] => d
    	[1] => b
    	[2] => c
    	[3] => a
    )
    */

    Ruby

    a = [ "a", "b", "c", "d" ];
    puts a.sort_by{ rand };
    # => ["d", "b", "c", "a"]