Introduction To Ruby
Random Numbers

Random Integers

The following example generates random integers,

# Random Integers

a = rand(10) # Integer from 0 - 9
puts a

b = rand(10)+10 # Integer from 10 - 19
puts b

c = rand(10)-5 # Integer from -5 to 4
puts c


Study these examples carefully. The number in the brackets is referred to as max. The random number that is generated will be from 0 to max - 1. Almost all programming languages use this kind of exclusivity when specifying random integers. People who are new to programming often fail to read references carefully and wonder why, for example, their dice program cannot generate a 6. Adding or subtracting from the number that is generated allows you to generate random numbers within a given range.

Random Floats

If you don't place a number in the brackets, you generate a floating point number that is greater than or equal to 0.0 and less than 1.0. The following example demonstrates this,

# Random Floats

a = rand() # Float greater than or equal to 0.0, less than 1.0
puts a

b = rand()*10 # Float greater than or equal to 0.0, less than 10.0
puts b


Using multiplication, addition and subtraction, you can get a random floating point number in the range that you want.


  1. Make a program that simulates the rolling of two dice. Output the result of each roll as well as the total.
  2. Output 6 lotter numbers (1 - 49). Don't worry about duplicates at this stage but make sure that it is possible to generate a 49.