返回随机布尔值的最佳方法

在构建假种子数据时,我已经使用它返回 truefalse一段时间了。只是想知道是否有人有一个更好的,更简洁或冗长的方式返回 truefalse

rand(2) == 1 ? true : false
28563 次浏览

A declarative snippet using Array#sample:

random_boolean = [true, false].sample

How about removing the ternary operator.

rand(2) == 1

I usually use something like this:

rand(2) > 0

You could also extend Integer to create a to_boolean method:

class Integer
def to_boolean
!self.zero?
end
end

I like to use rand:

rand < 0.5

Edit: This answer used to read rand > 0.5 but rand < 0.5 is more technically correct. rand returns a result in the half-open range [0,1), so using < leads to equal odds of half-open ranges [0,0.5) and [0.5,1). Using > would lead to UNEQUAL odds of the closed range [0,0.5] and open range (.5,1).