Chuck Bergeron
Chuck Bergeron

Reputation: 2046

Best way of returning a random boolean value

I've been using this for some time to return either true or false when building fake seed data. Just wondering if anybody has a better, more succinct or verbose way of returning either true or false.

rand(2) == 1 ? true : false

Upvotes: 116

Views: 31756

Answers (4)

JesseG17
JesseG17

Reputation: 704

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

Upvotes: 25

tokland
tokland

Reputation: 67900

A declarative snippet using Array#sample:

random_boolean = [true, false].sample

Upvotes: 272

a&#39;r
a&#39;r

Reputation: 37009

How about removing the ternary operator.

rand(2) == 1

Upvotes: 37

Adam Eberlin
Adam Eberlin

Reputation: 14205

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

Upvotes: 4

Related Questions