You can simply use random_number . If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.
Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.
Just use Array#sample : [:foo, :bar]. sample # => :foo, or :bar :-) It is available in Ruby 1.9.
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.
Just note the difference between the range operators:
3..10 # includes 10
3...10 # doesn't include 10
See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.
For 10 and 10**24
rand(10**24-10)+10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With