Module: UtilityPack::CoreExtensions::Array

Included in:
Array
Defined in:
lib/utility_pack/core_ext/array.rb

Instance Method Summary collapse

Instance Method Details

#random(count = 1) ⇒ Object

returns a random element from the array if count is specified, a array of unique random elements is returned



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/utility_pack/core_ext/array.rb', line 7

def random(count = 1)
  
  raise "Invalid argument (count must be >1)" if count < 1
  
  if count == 1
    self[rand(self.size)]
  else
    raise "Invalid argument.  The size of the array is #{self.size} and \
      you are requesting #{count} random elements" if count > self.size
    
    r = []
    while r.size != count
      tmp = self[rand(self.size)]
      r << tmp unless r.include?(tmp)
    end
    
    if count == 1
      r = r[0]
    end
    r
  end
end