Hi. Total noob, very simple question. Can anyone tell me how I can
generate a random number between two specific figures (between 60 and
2000, for instance)/
Thanks
Hi,
A good place to start when you're new and don't know is the
documentation. Thankfully the entire ruby API, which outlines all the
libraries and modules that come both as core Ruby libraries and
standard Ruby libraries. Try
www.ruby-doc.org, and have a look at the
Core API. Specifically, you're going to want the Kernel module.
Have a look at the rand method. It will not allow you to specify a
range, but will generate a number between 0 and (max1 - 1). If you
make ((max1 - 1) - 0) equal to your range (which in the case of your
example is 2000 - 60 = 1940 + 1 = 1941), and then scale it up by 60,
youll always end up with a random number in the range you're looking
for.
So, a set of calls like this:
R_OFFSET = 60
random_num = Kernel.rand(1941) + R_OFFSET
will give you a random number in the range 60-2000. Try and use a
constant (R_OFFSET) to handle the offset, no one likes magic numbers.
Keep in mind that Ruby's random numbers are only pseudorandom, so if
you need real random numbers you should look into something a little
more robust than Kernel.rand
Thanks,
cb