Misha Moroshko Misha Moroshko - 1 year ago 142
Ruby Question

How to generate a random number between a and b in Ruby?

To generate a random number between 3 and 10, for example, I use:

rand(8) + 3

Is there a nicer way to do this (something like
rand(3, 10)
) ?

Answer Source

UPDATE: Ruby 1.9.3 Kernel#rand also accepts ranges



Converting to array may be too expensive, and it's unnecessary.





Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.

But anyway, generating array need resources, and solution you already wrote is the best, you can do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download