Class: Chance

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/chance/chance.rb,
lib/chance/version.rb

Constant Summary collapse

VERSION =
"0.5.2"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(percent) ⇒ Chance

Returns a new instance of Chance.



31
32
33
34
# File 'lib/chance/chance.rb', line 31

def initialize(percent)
  @odds = percent
  @happens = @odds.to_f > Kernel.rand(100)
end

Instance Attribute Details

#eventObject (readonly)

Returns the value of attribute event.



2
3
4
# File 'lib/chance/chance.rb', line 2

def event
  @event
end

#happensObject (readonly) Also known as: happens?

Returns the value of attribute happens.



2
3
4
# File 'lib/chance/chance.rb', line 2

def happens
  @happens
end

#oddsObject (readonly)

Returns the value of attribute odds.



2
3
4
# File 'lib/chance/chance.rb', line 2

def odds
  @odds
end

Class Method Details

.case(*chances) ⇒ Object



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

def self.case(*chances)
  raise "Chances don't add to 100" unless chances.inject(0) {|sum, chance| sum + chance.to_f } == 100
  ranges = []
  chances = chances.sort_by{|c| c.to_f}
  chances.each_with_index do |chance, i|
    chance = chance.to_f
    range =
      if i == 0
        0..chance
      elsif i == chances.size - 1
        @last_chance..100
      elsif @last_chance
        @last_chance..chance
      end
    @last_chance = range.begin
    ranges << range
  end
  num = Kernel.rand(100)
  ranges.each_with_index do |r, i|
    if r.include? num
      return chances[i].event.call
    end
  end
end

Instance Method Details

#*(other_chance) ⇒ Object



54
55
56
# File 'lib/chance/chance.rb', line 54

def *(other_chance)
  Chance.new(self.odds.of(chance.odds.to_f))
end

#<=>(other_chance) ⇒ Object



58
59
60
# File 'lib/chance/chance.rb', line 58

def <=>(other_chance)
  odds.to_f <=> other_chance.to_f
end

#identical(other_chance) ⇒ Object Also known as: identical?



62
63
64
# File 'lib/chance/chance.rb', line 62

def identical(other_chance)
  self == other_chance && self.happens? == other.happens?
end

#of(&block) ⇒ Object



36
37
38
# File 'lib/chance/chance.rb', line 36

def of(&block)
  yield if happens?
end

#to_fObject Also known as: value



45
46
47
# File 'lib/chance/chance.rb', line 45

def to_f
  odds.to_f
end

#to_sObject



50
51
52
# File 'lib/chance/chance.rb', line 50

def to_s
  "A #{odds.to_f} percent chance"
end

#will(&block) ⇒ Object



40
41
42
43
# File 'lib/chance/chance.rb', line 40

def will(&block)
  @event = block
  self
end