Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/mod_array.rb

Instance Method Summary collapse

Instance Method Details

#random(array = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/mod_array.rb', line 2

def random array = nil
  if array
    raise ArgumentError, "weight array must match length of array (#{length})" unless length == array.length
    max_weight = 0
    array.each {|n| max_weight += n }
    target_weight = rand max_weight
    index = 0
    index_weight = array[index]
    while index_weight <= target_weight
      index += 1
      index_weight += array[index]
    end
    self[index]
  else
    self[rand length]
  end
end