← homeProgramming (Програмування)

How to get a random logical value true or false in Ruby?

How to get a random logical value true or false in Ruby? Getting a random boolean value in Ruby.

This content has been automatically translated from Ukrainian.
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:
Screenshot 2023-05-03 at 21.01.03.png
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
Screenshot 2023-05-03 at 21.22.23.png
After that, we take the first [0] or second [1] element of the shuffled array:
[true, false].shuffle[0]
or
[true, false].shuffle[1]
Screenshot 2023-05-03 at 21.23.32.png
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:
gem install 'faker'
we include the library
require 'faker' 
We get a random boolean value using Faker:
Faker::Boolean.boolean
require 'faker'

=> true


Faker::Boolean.boolean

=> false

Faker::Boolean.boolean

=> true
Screenshot 2023-05-03 at 21.44.17.png
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).

🔥 More posts

All posts
Programming (Програмування)May 16, '23 20:02

What is Origin in Git?

What is Origin in Git? Why write origin in a git command? When and why are aliases needed in git ...