How to Generate an Array of Random Numbers in Ruby

09/24/2021

Contents

In this article, you will learn how to generate an array of random numbers in Ruby.

Generating an array of random numbers

In Ruby, there are several ways to generate an array of random numbers. Here are some of the most common methods:

Using the rand method

The rand method generates a random number between 0 and 1. To generate an array of random numbers using this method, you can use the map method along with rand to generate the desired number of random numbers.

random_numbers = Array.new(10) { rand }

This will generate an array of 10 random numbers between 0 and 1.

Using the Random class

The Random class provides more control over the generation of random numbers. You can create an instance of the Random class and use its methods to generate random numbers. For example, you can use the rand method of the Random class to generate a random number between 0 and a specified maximum value:

random = Random.new
random_numbers = Array.new(10) { random.rand(100) }

This will generate an array of 10 random numbers between 0 and 100.

Using the SecureRandom module

The SecureRandom module provides a secure way to generate random numbers. You can use the random_number method of the SecureRandom module to generate a random number between 0 and 1, and then use the map method to generate an array of random numbers:

require 'securerandom'
random_numbers = Array.new(10) { SecureRandom.random_number }

This will generate an array of 10 secure random numbers between 0 and 1.

Using the Array#shuffle method

You can also generate an array of random numbers by creating an array of consecutive integers and shuffling them using the shuffle method:

random_numbers = (1..10).to_a.shuffle

This will generate an array of 10 random numbers between 1 and 10.

Using the Array#sample method

You can also use the sample method to generate an array of random numbers. The sample method returns a random element from the array. To generate an array of random numbers, you can use the map method along with the sample method:

random_numbers = Array.new(10) { (1..100).to_a.sample }

This will generate an array of 10 random numbers between 1 and 100.