aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/array/random_access.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/array/random_access.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/array/random_access.rb22
1 files changed, 18 insertions, 4 deletions
diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb
index 67c322daea..7a4836cecd 100644
--- a/activesupport/lib/active_support/core_ext/array/random_access.rb
+++ b/activesupport/lib/active_support/core_ext/array/random_access.rb
@@ -1,6 +1,20 @@
class Array
- # Returns a random element from the array.
- def random_element
- self[Kernel.rand(length)]
- end
+ # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/
+ 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 \ No newline at end of file