0

I want a Ruby method to return true based on a percent probability.

def random_true(probability)
    # Math to randomly return true based on weighted probability 
end

Then I could just call random_true(0.4) (implying 40% chance of it returning true).

Would also be fine if it was a simple one-liner that didn't even need a method.

i.e. return true if XYZ

Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • 2
    `rand <= probability` (or `probability <= rand`) is all you need. See [Kernel#rand](http://ruby-doc.org/core-2.4.0/Kernel.html#method-i-rand). That is, `rand` generates a pseudo-random number between zero and one, so `rand <= probability` returns `true` or `false`. Incidentally, where you say "percent probability" I think you mean just "probability", as probabilites are numbers (not percents) between zero and one. – Cary Swoveland May 20 '18 at 21:28
  • 1
    @CarySwoveland you gave this same answer in a question I asked a while ago https://stackoverflow.com/questions/39585659/coin-flipper-with-n-probability-of-heads – max pleaner May 20 '18 at 21:35

0 Answers0