Sha256: 7f9ba6255345a693f91c0b642566094f9d01f00a96f97f5e0b7b3b9c3584b91a

Contents?: true

Size: 1.05 KB

Versions: 47

Compression:

Stored size: 1.05 KB

Contents

unless Array.method_defined? :sample
  require 'backports/tools/arguments'

  class Array
    def sample(n = Backports::Undefined, options = Backports::Undefined)
      if options == Backports::Undefined && n.respond_to?(:to_hash)
        n, options = options, n
      end
      rng = Backports.coerce_to_option(options, :random) unless options == Backports::Undefined
      generator = if rng.respond_to? :rand
        Proc.new do |nb|
          r = Backports::coerce_to_int(rng.rand(nb))
          raise RangeError, "random generator returned #{r} which is not in 0...#{nb}" if r < 0 || r >= nb
          r
        end
      else
        Kernel.method(:rand)
      end
      return self[generator.call(size)] if n == Backports::Undefined
      n = Backports.coerce_to_int(n)
      raise ArgumentError, "negative array size" if n < 0
      n = size if n > size
      result = Array.new(self)
      n.times do |i|
        r = i + generator.call(size - i)
        result[i], result[r] = result[r], result[i]
      end
      result[n..size] = []
      result
    end
  end
end

Version data entries

47 entries across 47 versions & 4 rubygems

Version Path
backports-3.25.0 lib/backports/1.9.1/array/sample.rb
backports-3.24.1 lib/backports/1.9.1/array/sample.rb
backports-3.24.0 lib/backports/1.9.1/array/sample.rb
backports-3.23.0 lib/backports/1.9.1/array/sample.rb
backports-3.22.1 lib/backports/1.9.1/array/sample.rb
backports-3.22.0 lib/backports/1.9.1/array/sample.rb
backports-3.21.0 lib/backports/1.9.1/array/sample.rb
backports-3.20.2 lib/backports/1.9.1/array/sample.rb
backports-3.20.1 lib/backports/1.9.1/array/sample.rb
backports-3.20.0 lib/backports/1.9.1/array/sample.rb
backports-3.19.0 lib/backports/1.9.1/array/sample.rb
backports-3.18.2 lib/backports/1.9.1/array/sample.rb
backports-3.18.1 lib/backports/1.9.1/array/sample.rb
backports-3.18.0 lib/backports/1.9.1/array/sample.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/1.9.1/array/sample.rb
backports-3.17.2 lib/backports/1.9.1/array/sample.rb
backports-3.17.1 lib/backports/1.9.1/array/sample.rb
backports-3.17.0 lib/backports/1.9.1/array/sample.rb
backports-3.16.1 lib/backports/1.9.1/array/sample.rb
backports-3.16.0 lib/backports/1.9.1/array/sample.rb