Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/scrambler/core_ext.rb
Overview
borrowed from activesupport
Instance Method Summary collapse
Instance Method Details
#sample(n = nil) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/scrambler/core_ext.rb', line 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.})" 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 |