Ruby
Coding
Programming
Random Number Generation
Coding Tutorials

How to get a random number in Ruby

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Ruby, generating random numbers is a common requirement, whether for games, simulations, or sampling data for applications. Ruby provides several methods to generate random numbers, primarily using the Random class. Here's a comprehensive guide on how to obtain random numbers.

The rand Method

The simplest way to generate a random number in Ruby is by using the rand method. This method can be used in several ways:

  1. No Arguments: If called without any arguments, rand returns a floating-point number between 0.0 and 1.0.
ruby
    random_number = rand
    puts random_number
  1. With an Integer: If you pass an integer n to rand(n), it returns an integer from 0 to n-1.
ruby
    random_number = rand(10)  # Generates a number from 0 to 9
    puts random_number
  1. Range Argument: You can also pass a range to rand to get a random number within the specified range.
ruby
    random_number = rand(1..10)  # Generates a number from 1 to 10
    puts random_number

The Random Class

For more complex needs, Ruby provides the Random class, which offers methods and behaviors that allow more control over random number generation.

Creating a Random Number Generator

You can create your own random number generator (RNG) instance using Random.new. This can be handy when you want to maintain the state of your random number sequence:

ruby
rng = Random.new
random_number = rng.rand
puts random_number

Specifying a Seed

The Random.new method can accept a seed parameter to initialize the RNG. This is particularly useful for scenarios where you need reproducible sequences of random numbers:

ruby
1rng1 = Random.new(1234)
2rng2 = Random.new(1234)
3
4# Both will print the same sequence of random numbers
5puts rng1.rand
6puts rng2.rand

Generating Numbers within a Range

Similar to the rand method, you can also use the rand method of an instance of Random to generate numbers within a specific range:

ruby
rng = Random.new
random_number = rng.rand(100..200)
puts random_number

Secure Random Numbers

For cryptographic or security-related applications, Ruby's Standard Library offers the SecureRandom module which provides methods to generate random numbers, strings, and hex values securely. This is crucial when generating data that involves security components such as tokens, passwords, etc.

ruby
1require 'securerandom'
2
3secure_number = SecureRandom.random_number(100)  # Random number between 0 and 99
4secure_hex = SecureRandom.hex(10)               # Random hex string of length 20
5puts secure_number
6puts secure_hex

Summary Table

MethodExampleDescription
randrand, rand(10), rand(1..10)Simple random floats or integers within a range.
Random.newRandom.new.randCreates a new RNG for controlled sequences.
SecureRandomSecureRandom.hex(10)Generates secure random values for cryptography.

Subtopics

  • Mathematical Basis of RNGs: Discusses how computers generate random numbers based on mathematical algorithms.
  • Applications of Random Numbers: Examples of how random numbers are used in real-world software projects.
  • Comparison with Other Languages: How Ruby's random number generation compares with similar mechanisms in other programming languages like Python or JavaScript.

Understanding these aspects of Ruby's random number generation capabilities will allow you to effectively utilize randomness in your applications, whether for simple shuffling, complex simulations, or secure cryptographic operations.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions