instance method sample

Ruby on Rails 3.0.20

Since v3.0.20 Last seen in v3.2.22.5

Available in: v3.0.20 v3.1.12 v3.2.22.5

Signature

sample(n=nil)

Backport of Array#sample based on Marc-Andre Lafortune’s github.com/marcandre/backports/ Returns a random element or n random elements from the array. If the array is empty and n is nil, returns nil. if n is passed, returns [].

[1,2,3,4,5,6].sample    # => 4
[1,2,3,4,5,6].sample(3) # => [2, 4, 5]
           [].sample    # => nil
           [].sample(3) # => []

Parameters

n opt = nil
Source
# File activesupport/lib/active_support/core_ext/array/random_access.rb, line 10
  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: obj.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 10 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Array

Type at least 2 characters to search.

↑↓ navigate · open · esc close