How to generate a random number between a and b in Ruby?
UPDATE: Ruby 1.9.3 Kernel#rand
also accepts ranges
rand(a..b)
http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
Converting to array may be too expensive, and it's unnecessary.
(a..b).to_a.sample
Or
[*a..b].sample
Array#sample
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.
Random.new.rand(a..b)
Where a
is your lowest value and b
is your highest value.
rand(3..10)
Kernel#rand
When max is a Range, rand returns a random number where range.member?(number) == true.