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 :
1
2
3
4
rand(1..6)
# => 4
rand(1..6)
# => 2
Note that without range, output will be from 0 to N.
1
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.
1
2
SecureRandom.random_number(2)
# => will output 0 or 1
1
2
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.
1
2
irb $> SecureRandom.random_number
# => 0.25562499980914666
1
2
irb $> SecureRandom.random_number
# => 0.8439818588730659
The Random class
1
2
3
4
5
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 :
1
2
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
orRandom.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)