array_rand

  • We can find a random element of an array in Ruby by accessing a random element of the array with using a combination of the Array#[] method with Kernel#rand.

    PHP

    $fruit = array('apple', 'banana', 'kiwi', 'lime');
    $key   = array_rand($fruit);
    print $fruit[$key]."\n";
    // => 'lime'

    Ruby

    fruit = ["apple", "banana", "kiwi", "lime"]
    fruit[rand(fruit.length)]
    # => "lime"

    The Rails ActiveSupport library provides a simple shortcut method for this as Array#rand.

    Rails

    fruit = ["apple", "banana", "kiwi", "lime"]
    fruit.rand
    # => "lime"

    see also

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.