Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of returning a random boolean value

Tags:

ruby

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 
like image 570
Chuck Bergeron Avatar asked Nov 04 '11 16:11

Chuck Bergeron


People also ask

How do you generate a random Boolean value in Python?

Use random. getrandbits() to get a random boolean value Call random. getrandbits(k) with k set to 1 to get a single random bit. A bit is either 0 (representing False ) or 1 (representing True ). Use bool() to convert the random bit into a bool.

How do you generate a random Boolean in C++?

bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);

What value does a Boolean value return?

The Boolean object represents a truth value: true or false .

What is random nextBoolean?

The nextBoolean() method of Random class returns the next pseudorandom, uniformly distributed boolean value from the random number generator's sequence.


2 Answers

A declarative snippet using Array#sample:

random_boolean = [true, false].sample 
like image 176
tokland Avatar answered Oct 09 '22 22:10

tokland


How about removing the ternary operator.

rand(2) == 1 
like image 44
a'r Avatar answered Oct 09 '22 21:10

a'r