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

RubyRandomRange

Ruby Problem Overview


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)) ?

Ruby Solutions


Solution 1 - 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.

Solution 2 - Ruby

Random.new.rand(a..b) 

Where a is your lowest value and b is your highest value.

Solution 3 - Ruby

rand(3..10)

Kernel#rand

> When max is a Range, rand returns a random number where range.member?(number) == true.

Solution 4 - Ruby

Just note the difference between the range operators:

3..10  # includes 10
3...10 # doesn't include 10

Solution 5 - Ruby

def random_int(min, max)
    rand(max - min) + min
end

Solution 6 - Ruby

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.

Solution 7 - Ruby

For 10 and 10**24

rand(10**24-10)+10

Solution 8 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMisha MoroshkoView Question on Stackoverflow
Solution 1 - RubyNakilonView Answer on Stackoverflow
Solution 2 - Rubyuser1782571View Answer on Stackoverflow
Solution 3 - RubyDorianView Answer on Stackoverflow
Solution 4 - RubyYaniv PreissView Answer on Stackoverflow
Solution 5 - RubyChasephView Answer on Stackoverflow
Solution 6 - RubybnaulView Answer on Stackoverflow
Solution 7 - RubySayan MalakshinovView Answer on Stackoverflow
Solution 8 - RubyVadym TyemirovView Answer on Stackoverflow