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 :

# => 4
# => 2

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

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


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.

# => will output 0 or 1
# => 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 =
# => 22
# => "\xBAVZ"

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

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

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, excerpt for a few noticeable exceptions :

  • You use it only once in your application, for example MyApp::Random = 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.