How do I generate a random number between 0 and n?
How do I generate a random number between 0 and n ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
rand(range)From Ruby Random Numbers:
As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own
Randomclass (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:
Note:
Using
Random.new.rand(20..30)(usingRandom.new) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).But if you don’t use
Random.new, then the class methodrandonly takes amaxvalue, not aRange, as banister (energetically) points out in the comment (and as documented in the docs forRandom). Only the instance method can take aRange, as illustrated by generate a random number with 7 digits.This is why the equivalent of
Random.new.rand(20..30)would be20 + Random.rand(11), sinceRandom.rand(int)returns “a random integer greater than or equal to zero and less than the argument.”20..30includes 30, I need to come up with a random number between 0 and 11, excluding 11.