shuffle

  • We can shuffle an array in Ruby using a combination of Enumberable#sort_by and Kernel#rand. It is important to note that the original array is modified by PHP’s shuffle function, but is not modified in the Ruby version.

    PHP

    $fruit = array('apple', 'banana', 'kiwi', 'lime');
    shuffle($fruit);
    var_export($fruit);
    // array(0 => 'kiwi', 1 => 'banana', 2 => 'lime', 3 => 'apple')

    Ruby

    fruit = ["apple", "banana", "kiwi", "lime"]
    result fruit.sort_by { rand }
    p result
    # => ["lime", "kiwi", "apple", "banana"]

    see also

sha1_file sizeof

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.