Class: Chance
- Inherits:
-
Object
- Object
- Chance
- Includes:
- Comparable
- Defined in:
- lib/chance/chance.rb,
lib/chance/version.rb
Constant Summary collapse
- VERSION =
"0.5.2"
Instance Attribute Summary collapse
-
#event ⇒ Object
readonly
Returns the value of attribute event.
-
#happens ⇒ Object
(also: #happens?)
readonly
Returns the value of attribute happens.
-
#odds ⇒ Object
readonly
Returns the value of attribute odds.
Class Method Summary collapse
Instance Method Summary collapse
- #*(other_chance) ⇒ Object
- #<=>(other_chance) ⇒ Object
- #identical(other_chance) ⇒ Object (also: #identical?)
-
#initialize(percent) ⇒ Chance
constructor
A new instance of Chance.
- #of(&block) ⇒ Object
- #to_f ⇒ Object (also: #value)
- #to_s ⇒ Object
- #will(&block) ⇒ Object
Constructor Details
Instance Attribute Details
#event ⇒ Object (readonly)
Returns the value of attribute event.
2 3 4 |
# File 'lib/chance/chance.rb', line 2 def event @event end |
#happens ⇒ Object (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 |
#odds ⇒ Object (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_f ⇒ Object Also known as: value
45 46 47 |
# File 'lib/chance/chance.rb', line 45 def to_f odds.to_f end |
#to_s ⇒ Object
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 |