Reputation: 2046
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
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
Reputation: 67900
A declarative snippet using Array#sample:
random_boolean = [true, false].sample
Upvotes: 272
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