Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to get a random number in Ruby

How do I generate a random number between 0 and n?
by

2 Answers

kshitijrana14
You can generate a random number with the 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 generates a number between 0 to 8
rand(0 .. 9) # this generates a number between 0 to 9
rand(1 .. 50) # this generates a number between 1 to 50
#rand(m .. n) # m is the start of the number range, n is the end of number range
sandhya6gczb
Use rand(range)
If you need percentage then just use rand()
If you need an integer value from 1 to x, not including x, call rand(x).
If you need a number in a specific range, call rand(x,y) where x is the lower range and y is upper range

Login / Signup to Answer the Question.