How to Get a Random Number in Ruby

How to get a random number in Ruby

Use rand(range)

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

  • Using Random.new.rand(20..30) (using Random.new) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).

  • But if you don't use Random.new, then the class method rand only takes a max value, not a Range, as banister (energetically) points out in the comment (and as documented in the docs for Random). Only the instance method can take a Range, as illustrated by generate a random number with 7 digits.

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

Ruby on Rails - Generating random number that does not exist in database

To generate a random number and ensuring that the number doesn't exist in the database I would do something like this:

before_create :assign_unique_case_number

validates! :case_number, uniqueness: true

private

CASE_NUMBER_RANGE = (10_000..99_999)

def assign_unique_case_number
self.case_number = loop do
number = rand(CASE_NUMBER_RANGE)
break number unless Case.exists?(case_number: number)
end
end

Please note that the more case there are in the database the longer it might take to find an unused number. Therefore I suggest using greater numbers right from the start. Greater numbers have another advantage: They are harder to guess what might or might not be important in your application.

Furthermore: Rails cannot guarantee that uniqueness in the database. There might be race conditions that lead to duplicates. The only way to avoid that is to add a unique index to the database column in a migration like this:

add_index :cases, :case_number, unique: true

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.

Generate a random number with a seed between a range in ruby

You can create a special/designated random number generator with any seed value you like:

special = Random.new 42 # create a new instance of Random seeded with 42
20.times { p special.rand(5..10) } # generate 20 random ints in range 5 to 10

Your special instance of Random is independent of kernel#rand unless you use srand to initialize it with the same seed value.

How to print out a random number between a range?

Give this a shot.

<%= [*5..30].sample %>

...or...

<%= rand(5..30) %>


Related Topics



Leave a reply



Submit