Take the 2-minute tour ×

In Ruby, how do you generate a random number between 0 and n?

share|improve this question
add comment

10 Answers

up vote 464 down vote accepted

What is wrong with rand(range)?

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.

As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]


This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

share|improve this answer
Thanks, VonC. I eventually did google for the answer, but I looked here for and didn't find the answer, so I thought it might be a useful addition. That's the purpose of SO, right? –  Mark A. Nicolosi Oct 13 '08 at 18:12
No problem, you have SO perfectly figured ;) –  VonC Oct 13 '08 at 18:21
Yup, SO is just a place for people too lazy to use google. –  Justin Nov 5 '09 at 18:05
What's funny is that this post is now the first Google result. –  ahsteele Nov 17 '09 at 17:39
Isn't this terribly non-ruby-like? I thought everything is an object, least-surprise and that... –  Yar Jan 26 '10 at 18:50
show 9 more comments

You can use rand(42-10) + 10 to get a random number between 10 and 42 (where 10 is inclusive and 42 exclusive).

Ruby 1.9.2 also introduces the Random class so you can now create your own random number generator objects and has a nicer API:

r = Random.new
r.rand(10...42) # => 22

The Random class itself acts as a random generator, so you call directly:

Random.rand(42-10) + 10 # => same as rand(42-10) + 10

In Ruby 1.9.3, you are able to call:

Random.rand(10...42) # or simply `rand(10...42)`

Available for all versions of Ruby by requiring my backports gem.

Notes on Random.new

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 proporties of the random generator itself.

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new and use it everywhere else.

The cases where Random.new is helpful are the following:

  • you want to use the new API (like bytes, or rand with a range argument in Ruby 1.9.2)
  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)
share|improve this answer
Excellent! +1. I have completed my own answer to reflect that new feature (and mentioning your contribution with Bug #3104 ;) ). –  VonC May 5 '10 at 14:20
How does the backports gem work, in broad strokes? –  Yar May 5 '10 at 15:08
@yar: My backports gem is simply a collection of methods that are new to RUby 1.8.7, 1.9.1, 1.9.2, but implemented in Ruby. I use RubySpec to insure that the results are compatible with Ruby. –  Marc-André Lafortune May 5 '10 at 15:16
Random.rand(10..42) does not work. The Random.rand class method does not accept a range. (Ruby 1.9.2p180) –  banister Jun 27 '11 at 7:46
@banister: wow, I was convinced that the new api (rand with range, bytes, etc...) was available directly through the Random object. rand with range will be in 1.9.3, and I'll make a feature request for bytes. I've edited my answer –  Marc-André Lafortune Jun 27 '11 at 14:20
show 7 more comments

If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom module found its way from ActiveSupport to the ruby core in 1.9.2+. So without the need for a full blown framework:

require 'securerandom'

p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88

p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409

p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)

share|improve this answer
What about if you need 4 digits random number? –  onurozgurozkan Feb 1 at 22:12
add comment

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.

share|improve this answer
Yes, it's builtin in the Kernel module. –  Christoph Schiessl Oct 13 '08 at 19:18
Ahh, thanks Chrisoph. –  Mark A. Nicolosi Oct 13 '08 at 19:43
add comment

What about this?

n = 3
share|improve this answer
add comment

Apparently srand is called when the ruby interpreter is started.

Therefore unless you have a specific need to reset the seed - extra calls to srand are unnecessary.

share|improve this answer
The current version of daemons gems, does not call srand on all forked processes, and calling Random.rand() without first calling srand will cause a segmentation fault. –  Michael Irey Aug 8 '12 at 18:10
add comment

You can random number with rand method. The argument passed to the rand method should be an integer or a range, and returns a corresponding random number within the range:

rand(9)       # this generator a number between 0 to 8
rand(0 .. 9)  # this generator a number between 0 to 9
rand(1 .. 50) # this generator a number between 1 to 50
#rand(m .. n) # m is the start of generator number range, n is the end of generator number range
share|improve this answer
It can be a Float as well. rand(1.1..2.7) works. –  pisaruk Dec 2 '13 at 12:25
add comment

This link is going to be helpful regarding this;


And some more clarity below over the random numbers in ruby;

Generate an integer from 0 to 10

puts (rand() * 10).to_i

Generate a number from 0 to 10 In a more readable way

puts rand(10)

Generate a number from 10 to 15 Including 15

puts rand(10..15)

Non-Random Random Numbers

Generate the same sequence of numbers every time the program is run


Generate 10 random numbers

puts (0..10).map{rand(0..10)}
share|improve this answer
Also you can follow this blog for step by step very clear picture over random nos in ruby; sitepoint.com/tour-random-ruby –  Samar Kr Mishra Dec 24 '13 at 17:40
add comment

Don't forget to seed the RNG with srand() first.

share|improve this answer
What happens if you don't call srand()? –  Alex B Oct 17 '08 at 14:18
srand is automatically called with the seed being from the current time if it wasn't already called. –  Julian Feb 6 '10 at 9:25
add comment
rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.

share|improve this answer
I believe the range option is only available in ruby 1.9.3+. It didn't work in 1.9.2 when I tried at least. –  Batkins Dec 13 '12 at 21:24
add comment

protected by Elenasys Feb 21 at 3:06

