def random_int(min, max)
rand(max - min) + min
end
And here is a quick benchmark for both #sample
and #rand
:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
So, doing rand(a..b)
is the right thing
Just note the difference between the range operators:
3..10 # includes 10
3...10 # doesn't include 10
For 10 and 10**24
rand(10**24-10)+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.
rand(3..10)
When max is a Range, rand returns a random number where range.member?(number) == true.
Random.new.rand(a..b)
Where a
is your lowest value and b
is your highest value.
Source: Stackoverflow.com