Module: ActiveSupport::CoreExtensions::Array::RandomAccess

Included in:
Array
Defined in:
lib/active_support/core_ext/array/random_access.rb

Instance Method Summary collapse

Instance Method Details

#randObject

This method is deprecated because it masks Kernel#rand within the Array class itself, which may be used by a 3rd party library extending Array in turn. See

https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4555


10
11
12
13
# File 'lib/active_support/core_ext/array/random_access.rb', line 10

def rand # :nodoc:
  ActiveSupport::Deprecation.warn 'Array#rand is deprecated and will be removed in Rails 3. Use Array#sample instead', caller
  sample
end

#random_elementObject

Returns a random element from the array.



16
17
18
19
# File 'lib/active_support/core_ext/array/random_access.rb', line 16

def random_element # :nodoc:
  ActiveSupport::Deprecation.warn 'Array#random_element is deprecated and will be removed in Rails 3. Use Array#sample instead', caller
  sample
end

#sample(n = nil) ⇒ Object

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File '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