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 with2 + 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)
(usingRandom.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 methodrand
only takes amax
value, not aRange
, as banister (energetically) points out in the comment (and as documented in the docs forRandom
). Only the instance method can take aRange
, 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
Difference Between ≪%, ≪%=, ≪%# and -%≫ in Erb in Rails
How to Search File Text For a Pattern and Replace It With a Given Value
Ruby Function to Remove All White Spaces
How to Download a File from a Url and Save It in Rails
In Rails, How to Render Json Using a View
Is There a Performance Gain in Using Single Quotes VS Double Quotes in Ruby
Does Ruby Perform Tail Call Optimization
How to Override a Setter Method in Ruby on Rails
What's the Difference Between Equal, Eql, ===, and ==
Sudo Gem Install' or 'Gem Install' and Gem Locations
Why Doesn't Ruby Support Method Overloading
How to Make a Http Request Using Ruby on Rails