Module: RichEngine::Chance

Defined in:
lib/rich_engine/chance.rb

Overview

Random helpers for probability checks.

Class Method Summary collapse

Class Method Details

.of(value, rand_gen: method(:rand)) ⇒ Boolean

Returns true with the given probability.

Examples:

RichEngine::Chance.of(0.2) # 20% chance
RichEngine::Chance.of(20)  # also 20% (percent form)

Parameters:

  • value (Integer, Float)

    a probability as a fraction (0.2) or as a percentage (20); values greater than 1 are treated as percentages.

  • rand_gen (#call) (defaults to: method(:rand))

    a generator returning a float in [0, 1).

Returns:

  • (Boolean)

    whether the chance succeeded.



15
16
17
18
19
20
21
22
23
# File 'lib/rich_engine/chance.rb', line 15

def self.of(value, rand_gen: method(:rand))
  percent = if value > 1
    value / 100.0
  else
    value
  end

  rand_gen.call < percent
end

.of_one_in(value, rand_gen: method(:rand)) ⇒ Boolean

Returns true with a one-in-+value+ probability.

Examples:

RichEngine::Chance.of_one_in(10) # 1 in 10 chance

Parameters:

  • value (Integer, Float)

    the denominator of the odds.

  • rand_gen (#call) (defaults to: method(:rand))

    a generator returning a float in [0, 1).

Returns:

  • (Boolean)

    whether the chance succeeded.



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

def self.of_one_in(value, rand_gen: method(:rand))
  of(1 / value.to_f, rand_gen: rand_gen)
end