instance method sample

Ruby on Rails 2.3.18

Since v2.3.18 Last seen in v2.3.18

Signature

sample(n=nil)

Backport of Array#sample based on Marc-Andre Lafortune’s github.com/marcandre/backports/

Parameters

n opt = nil
Source
# File activesupport/lib/active_support/core_ext/array/random_access.rb, line 22
        def sample(n=nil)
          return self[Kernel.rand(size)] if n.nil?
          n = n.to_int
        rescue Exception => e
          raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})"
        else
          raise TypeError, "Coercion error: #{n}.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? ::Integer
          raise ArgumentError, "negative array size" if n < 0
          n = size if n > size
          result = ::Array.new(self)
          n.times do |i|
            r = i + Kernel.rand(size - i)
            result[i], result[r] = result[r], result[i]
          end
          result[n..size] = []
          result
        end

Defined in activesupport/lib/active_support/core_ext/array/random_access.rb line 22 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::CoreExtensions::Array::RandomAccess

Type at least 2 characters to search.

↑↓ navigate · open · esc close