PHP to Ruby
Convert PHP code into Ruby!
-
array_rand
Posted on February 16th, 2010 1 commentThe 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
One response to “array_rand”
-
Actually, this is just not true.
array_rand returns a random KEY of the givven array. So to get the value, you’d use:
$random_value = $users[array_rand($users)];
Might look strange, but is very smart, because like this you can have both the key and the value. Sort of like in ruby =) except in php in works for assoc arrays as well. SPL ftw!
Leave a reply
-


