Module: RandomPerson::Ratio

Defined in:
lib/randomperson/ratio.rb

Overview

Handles ratios for demographics e.g. 1 male for 1 female.

Instance Method Summary collapse

Instance Method Details

#ordmag(n) ⇒ Object

find the order of magnitude of a number for use with this module



19
20
21
22
23
24
25
26
# File 'lib/randomperson/ratio.rb', line 19

def ordmag( n )
  m = 10
  while m < 1000
    break if n.divmod(m).first == 0
    m *= 10
  end
  m
end

#presto_rangio(len, mag) ⇒ Object

use this method if you don’t have a ratio at all for an array and, hey presto! It’ll make one for you

Parameters:

  • len (Integer)

    Length

  • mag (Integer)

    Magnitude



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/randomperson/ratio.rb', line 32

def presto_rangio( len, mag )
  return [ ] unless len >= 1
  l, m = len, mag
  lower = 0
  presto = [ ]
  
  while l > 0
    # b = nil
    upper = m - l
    if l == 1
      b = upper
    else
      b = rand( upper - lower ) + lower
    end
    presto << (lower..b)   
    lower = b + 1
    l = l - 1
  end
  presto
end

#rangio(ratio = [1,1]) ⇒ Object

create a ratio that is made up of ranges to help hit with multiple valued ratios



8
9
10
11
12
13
14
15
# File 'lib/randomperson/ratio.rb', line 8

def rangio( ratio=[1,1] )
  sum = ratio.reduce(:+) #sum
  mult = 100.divmod( sum ).first #get a bigger spread of numbers
  ratio.map! { |n| n * mult }
  new_ratio = ratio.inject([0..0]) {|acc,n| acc + [acc.last.last ... (n + acc.last.last)] }
  new_ratio.shift #get rid of 0..0
  return new_ratio
end