File: shuffle.rb

package info (click to toggle)
ruby-backports 3.25.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,912 kB
  • sloc: ruby: 11,759; makefile: 6
file content (17 lines) | stat: -rw-r--r-- 427 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
unless Array.method_defined? :shuffle
  class Array
    def shuffle
      dup.shuffle!
    end

    # Standard in Ruby 1.8.7+. See official documentation[http://ruby-doc.org/core-1.9/classes/Array.html]
    def shuffle!
      raise TypeError, "can't modify frozen array" if frozen?
      size.times do |i|
        r = i + Kernel.rand(size - i)
        self[i], self[r] = self[r], self[i]
      end
      self
    end
  end
end