Best way of returning a random boolean value

Ruby

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

A declarative snippet using Array#sample:

random_boolean = [true, false].sample

Solution 2 - Ruby

How about removing the ternary operator.

rand(2) == 1

Solution 3 - Ruby

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

Solution 4 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChuck BergeronView Question on Stackoverflow
Solution 1 - RubytoklandView Answer on Stackoverflow
Solution 2 - Rubya'rView Answer on Stackoverflow
Solution 3 - RubyJesseG17View Answer on Stackoverflow
Solution 4 - RubyAdam EberlinView Answer on Stackoverflow