Method: Random::ArrayExtensions#rand_subset
- Defined in:
- lib/garcon/core_ext/random.rb
#rand_subset(number = nil, exclusive = true) ⇒ Object
Returns a random subset of an Array. If a number of elements is specified then returns that number of elements, otherwise returns a random number of elements upto the size of the Array.
By defualt the returned values are exclusive of each other, but if exclusive is set to false, the same values can be choosen more than once.
When exclusive is true (the default) and the number given is greater than the size of the array, then all values are returned.
197 198 199 200 201 202 203 |
# File 'lib/garcon/core_ext/random.rb', line 197 def rand_subset(number = nil, exclusive = true) number = SecureRandom.random_number(size) unless number number = number.to_int return sort_by{rand}.slice(0,number) if exclusive ri =[]; number.times { |n| ri << SecureRandom.random_number(size) } return values_at(*ri) end |