How to get a random number in Ruby

Posted May 5, 2022 - tagged ruby  ‐  2 min read

Let's see how to get a random number in Ruby

rand() method

Ruby's rand method belong to the kernel module. Which means you could use it in any Ruby's environment.

For example, if you want to emulate a dice roll, you would write :

rand(1..6)
# => 4
rand(1..6)
# => 2

Note that without range, output will be from 0 to N.

rand(6)    #=> gives a random number between 0 and 5.

random_number

Another possibility is tu use SecureRandom.random_number.

If a positive integer is given as X, random_number returns an integer like this : 0 <= random_number < X.

SecureRandom.random_number(2)
# => will output 0 or 1
SecureRandom.random_number(100)
# => will output any  number from 0 to 99

Without any argument, SecureRandom.random_number will output a float between 0 and 1.

irb $> SecureRandom.random_number
# => 0.25562499980914666
irb $> SecureRandom.random_number
# => 0.8439818588730659

The Random class

r = Random.new
r.rand(0...42) 
# => 22
r.bytes(3) 
# => "\xBAVZ"

Please note that the Random class act itself as a random generator, so that you can call it directly, like this :

Random.rand(0...42) 
# => same as rand(0...42)

Random.new

As stated in this excellent StackOverflow answer,

In most cases, the simplest is to use rand or Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

That means should not use Random.new, excerpt for a few noticeable exceptions :

  • You use it only once in your application, for example MyApp::Random = Random.new and use it everywhere else,
  • You want the ability to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)
  • You are writing a gem, and don't want a conflict with any sequence of rand/Random.rand that the main application might be using,
  • You want split reproducible sequences of random numbers (say one per Thread)

Build your MVP with Rails

👉 We are 2 Ruby-on-Rails lovers. By building BootrAils, we hope we will help you to launch your Startup idea (really) faster.
Take care ! Health first. 🙏
Shino & David.