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
While you can use
rand(42-10) + 10
to get a random number between10
and42
(where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:Available for all versions of Ruby by requiring my
backports
gem.Ruby 1.9.2 also introduced the
Random
class so you can create your own random number generator objects and has a nice API:The
Random
class itself acts as a random generator, so you call directly:Notes on
Random.new
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.If you use
Random.new
, you should thus call it as rarely as possible, for example once asMyApp::Random = Random.new
and use it everywhere else.The cases where
Random.new
is helpful are the following:rand
/Random.rand
that the main programs might be relying onRandom
objects can marshalled)you can do rand(range)
Don't forget to seed the RNG with srand() first.
Note that the range option is only available in newer(1.9+ I believe) versions of ruby.
This link is going to be helpful regarding this;
http://ruby-doc.org/core-1.9.3/Random.html
And some more clarity below over the random numbers in ruby;
Generate an integer from 0 to 10
Generate a number from 0 to 10 In a more readable way
Generate a number from 10 to 15 Including 15
Non-Random Random Numbers
Generate the same sequence of numbers every time the program is run
Generate 10 random numbers
Try
array#shuffle
method for randomization