1 module ActiveSupport #:nodoc:
2 module CoreExtensions #:nodoc:
3 module Array #:nodoc:
4 module RandomAccess
5 # This method is deprecated because it masks Kernel#rand within the Array class itself,
6 # which may be used by a 3rd party library extending Array in turn. See
7 #
8 # https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4555
9 #
10 def rand # :nodoc:
11 ActiveSupport::Deprecation.warn 'Array#rand is deprecated and will be removed in Rails 3. Use Array#sample instead', caller
12 sample
13 end
14
15 # Returns a random element from the array.
16 def random_element # :nodoc:
17 ActiveSupport::Deprecation.warn 'Array#random_element is deprecated and will be removed in Rails 3. Use Array#sample instead', caller
18 sample
19 end
20
21 # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/
22 def sample(n=nil)
23 return self[Kernel.rand(size)] if n.nil?
24 n = n.to_int
25 rescue Exception => e
26 raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})"
27 else
28 raise TypeError, "Coercion error: #{n}.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? ::Integer
29 raise ArgumentError, "negative array size" if n < 0
30 n = size if n > size
31 result = ::Array.new(self)
32 n.times do |i|
33 r = i + Kernel.rand(size - i)
34 result[i], result[r] = result[r], result[i]
35 end
36 result[n..size] = []
37 result
38 end unless method_defined? :sample
39 end
40 end
41 end
42 end