I need to make an event occur on a configurable x% of pageviews across all pageviews.
I want to make sure I'm thinking of the probability correctly here.
The following code runs every single pageview.
if I want event to occur 99% of the time
do_thing if SecureRandom.random_number(1..100) <= 99
if I want event to occur 10% of the time
do_thing if SecureRandom.random_number(1..100) <= 10
I know there are subtle nuance "gotchas" in probability and I wanted to make sure this is the best approach.
Your solution is ok in terms of probability calculations. But I would use the ruby method Kernel#rand
instead to save some space:
rand * 100 <= 99
or
rand(1..100) <= 99