In this section we will learn what the rand method is and how to use it in Ruby.
What is rand Method in Ruby?
The Ruby rand method is used to generate a random number whenever the method is getting called.
The method can be called either with or without any argument.
Let’s see the syntax of this method and then we will explain how to call the method in more details.
Ruby rand Method Syntax:
rand() rand(integer-number) rand(float-number) rand(range)
The method can be called with no argument, which in that case it will return a value between 0 to 1. (A floating value).
We can also pass an integer value to the method. Which in that case, it will produce a random number from 0 to the specified number.
Note that the target number we pass as the argument of the method is inclusive! Meaning if we pass the value 10 for example, as the argument of the method, we might get any integer number from 0 to 9 but not 10!
The method also takes a floating number as well! But even then, the return value will be a positive integer value!
Other than floating and integer numbers, we can pass a range into the rand method as well.
If we pass a range, the return value of the method will be a random number from the produced range.
Note that if we set either the starting or ending number of a range into a float number, then the return value of the rand method becomes a float type of number.
Example: using the rand method in Ruby
puts rand(4.3) puts rand(10) puts rand(1.2...4.5)
Output:
2 7 3.734732463191987