ある確率で実行したいとき、よく
if rand < 0.05 # 5% の確率で実行 end
のように書いていたが、ふと思いついて
class Integer
def percent
b = rand(100) < self
yield if b and block_given?
b
end
end
class Float
def percent
b = rand * 100 < self
yield if b and block_given?
b
end
end
と書いてみた。
5.percent do # 5% の確率で実行 end
結構いいかも? (意味的に言えば、5.percent == 0.05 となるべきなのかもしれないけど)