All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

How to get a random logical value true or false 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).

This post doesn't have any additions from the author yet.

03 May 17:46

What to do if the webcam is not working on macOS?

meme code
meme code@memecode
06 May 09:19

How to disable File Upload in the Trix editor?

meme code
meme code@memecode
10 May 17:40

How to use hex color codes in CSS with alpha values?

meme code
meme code@memecode
16 May 20:02

What is Origin in Git?

meme code
meme code@memecode
16 May 22:17

How to remove the space between inline and inline-block elements?

meme code
meme code@memecode
17 May 18:52

What is a loop in Javascript? How do for and while loops work in Javascript?

meme code
meme code@memecode
22 May 16:26

What is the difference between <%, <%=, <%# and -%> in ERB templates (Ruby on Rails)?

meme code
meme code@memecode