ruby can generate random numbers. A random number is unknown before running: it’s like telling the computer, give me any number.

Random numbers in computing are not truely random, they are often based on a pseudo random number generator algorithm. Eitherway for most program that degree of randomness is enough.
In this article you will learn how to generate random numbers.

Related course:
Learn Rails 5.2: Accelerated Web Development with Ruby on Rails

Random number in ruby

Example

The ruby program below generates a number between 0 and 10. The starting number (0) is not given and thus 0 is assumed as lowest number.

1
2
3
4
5
6
#!/usr/bin/ruby

r = Random.new
x = r.rand(10)

print("Random number: #{x}\n")

To generate a number between 20 and 40 you can use the code below:

1
2
3
4
5
6
#!/usr/bin/ruby

r = Random.new
x = 20 + r.rand(20)

print("Random number: #{x}\n")

Exercises

  1. Make a program that rolls a dice (1 to 6)
  2. Can you generate negative numbers?