Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

range

ruby

People also ask

Which of the following methods can be used in Ruby to get a random number?

You can simply use random_number . If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.

How do you create a range in Ruby?

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.

How do you generate an array of random numbers in Ruby?

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