In this article, you will learn how to generate random numbers in Ruby.
Using the rand method
In Ruby, you can generate random numbers using the built-in rand method. The rand method returns a random float between 0.0 and 1.0, and you can use it to generate random numbers within a specific range by scaling and shifting the output.
Here are a few examples:
Generating a random float between 0.0 and 1.0:
random_number = rand
Generating a random integer between 0 and 9:
random_number = rand(10)
Generating a random integer between 1 and 10:
random_number = rand(1..10)
Generating a random float between -5.0 and 5.0:
random_number = rand * 10 - 5