Sometimes you need to get a random boolean value true/false in Ruby. For example, when we are seeding a database in Rails and want to create objects that are as close to real as possible.
Option one. The sample method:
[true, false].sample
To test, as always - we run IRB (Interactive Ruby Shell) in the terminal:
Option two. Shuffle (the shuffle method) the array [true, false] and take the first or second element using an index.
We shuffle the elements in the array:
[true, false].shuffle
After that, we take the first [0] or second [1] element of the shuffled array:
[true, false].shuffle[0]
or
[true, false].shuffle[1]
Option three. Get a random number using the rand method and compare it to one of them.
1. Get a random 0 or 1;2. Compare the obtained number, for example with 1.
The random number:
rand(2)
=> 0
rand(2)
=> 1
Comparison:
rand(2) == 1
=> false
rand(2) == 1
=> true
Option four. Modified third option (with the zero? method):
rand(2).zero?
The zero? method asks if the number equals 0. Here it should be understood that rand(2) gives 0 or 1.
So zero? is a more elegant comparison than X == 0
Option 5. The Faker library.
You can almost always see the Faker library in a project, which provides fake data (for creating test objects).
In pure Ruby, you can install Faker:
I think there are many ways to get a random boolean value in Ruby. This is what makes Ruby cool. The same task can be done in many ways. And almost all of them will be 'correct'. Here, the question is about the speed of code execution and its style (how easy it is to read and understand).