How do I generate a random number between 0
and n
?
相关问题
- Question marks after images and js/css files in ra
- Using :remote => true with hover event
- Eager-loading association count with Arel (Rails 3
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
相关文章
- Ruby using wrong version of openssl
- Right way to deploy Rails + Puma + Postgres app to
- AWS S3 in rails - how to set the s3_signature_vers
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- How to add a JSON column in MySQL with Rails 5 Mig
- “No explicit conversion of Symbol into String” for
- form_for wrong number of arguments in rails 4
You can simply use
random_number
.If a positive integer is given as n,
random_number
returns an integer: 0 <=random_number
< n.Use it like this:
The output will be any number between 0 and 100.
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
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:
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 methodrand
only takes amax
value, 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..30
includes 30, I need to come up with a random number between 0 and 11, excluding 11.Easy way to get random number in ruby is,
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 fromActiveSupport
to the ruby core in 1.9.2+. So without the need for a full blown framework:It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)
Well, I figured it out. Apparently there is a builtin (?) function called rand:
If someone answers with a more detailed answer, I'll mark that as the correct answer.
Simplest answer to the question: