Best way of returning a random boolean value

A declarative snippet using Array#sample:

random_boolean = [true, false].sample

How about removing the ternary operator.

rand(2) == 1

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).


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

Tags:

Ruby