Sha256: 21b68654fee0661076a59f156241526af008049f97a07212eeb1566dbdea0763

Contents?: true

Size: 1.05 KB

Versions: 41

Compression:

Stored size: 1.05 KB

Contents

class Array
  # Backport of Array#sample based on Marc-Andre Lafortune's http://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 <tt>nil</tt>. if +n+ is passed, returns <tt>[]</tt>.
  #
  #   [1,2,3,4,5,6].sample    # => 4
  #   [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
  #              [].sample    # => nil
  #              [].sample(3) # => []
  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 unless method_defined? :sample
end

Version data entries

41 entries across 41 versions & 3 rubygems

Version Path
social_url_stats-0.0.1 vendor/ruby/1.9.1/gems/activesupport-3.0.0/lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.20 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.19 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.18 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.17 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.16 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.15 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.14 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.13 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.13.rc1 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.12 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.12.rc1 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.11 lib/active_support/core_ext/array/random_access.rb
messagebus_ruby_api-0.4.7 spec/ruby/1.9.1/gems/activesupport-3.0.9/lib/active_support/core_ext/array/random_access.rb
messagebus_ruby_api-0.4.4 spec/ruby/1.9.1/gems/activesupport-3.0.9/lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.10 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.10.rc1 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.9 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.9.rc5 lib/active_support/core_ext/array/random_access.rb
activesupport-3.0.9.rc4 lib/active_support/core_ext/array/random_access.rb