Ruby-Generate Random Numbers

In the following tutorial we will learn how to generate random numbers in ruby.

There are two ways in which random numbers can be generated. You might want to get a random number between zero and a number or you might want to get a random number between two numbers.Ruby easily allows us to do this. Let us go through each on of them.

In order to generate random numbers, we need to use the Random class provided by Ruby. You can view the documentation at http://www.ruby-doc.org/core-1.9.3/Random.html. If you notice in the documentation correctly, this class was added only in 1.9.2. So make sure you upgrade to the latest version of Ruby interpreter before you start working on this tutorial. You also have to be familiar with the range notation to use the tutorial.

Let us open up the irb. To generate random numbers in general we will be using rand method of the Random class. Use capital R while using the Random class because starting letter of classes must start with a capital letter in Ruby.

Generating a random number between zero and a number

Here is the situation in which I want to use this method. I want a random number less than 100. So I write Random.rand(100) on irb. This provides me with a random number between 0 and 100.



Generating a random number between two numbers

I want to generate a random number between 25 and 50. Here is how I do it in Ruby

I type in Random.rand(25..50) and I get a random number between 25 and 50



If you want to get negative random numbers multiply -1 in front of Random.rand method call. Here is my example