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.
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.
Trying to generate random number between a range based on an input, returns number outside range
if example_range = 11 || 12
is an assigning, resulting in example_range
variable assigned with value 11
.
Since this condition is truthy your program does not go further and returns
rand(212.502..255)
Double equal sign (==
) is used for comparison.
In your case you want to use something like
if [11, 12].include?(example_range)
P.S.
example_range = gets.chomp
returns a String object, not Integer - you need to convert the example_range
(using to_i
) before comparing with integers.
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.
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
Ruby: Generate random integers that add up to another number
Edit: see this answer
Just for fun (I'm sure it's not 100% for negatives etc...) :
class Fixnum
def rand_sum(n = 2)
arr = (n - 1).times.reduce([]) do |a, _|
curr_max = self - a.reduce(0, :+)
a << rand(0..curr_max)
end
arr << self - arr.reduce(0, :+)
end
end
11.rand_sum
=> [6, 5]
23.rand_sum 3
=> [10, 6, 7]
11.rand_sum 3
=> [6, 2, 3]
Get rand number from range
The to_a
method takes a lot of time to generate the array, which you don't need.
Just use:
rand(1..1000000000000000)
Negative random numbers
Let's say you want to generate a number between a and b you can always do that using this formula:
randomNum = (b-a)*prng.rand + a
So if you want a number between -8 and +7 for example then a=-8 and b=7 and your code would be
randomNum = (7-(-8))*prng.rand + (-8)
which is equivalent to
randomNum=15*prng.rand - 8
Generate Random Numbers Until a certain
The problem for this code is that you generate an infinite loop because num is always "", you need to update the variable num inside the while loop like this:
num = ""
while num != 7
num = rand(1..10)
puts num
end
puts "over"
in this case, you do not know when the loop will stop, but in each loop it can stop with probability 1/10, this is not a good practice, you nedd to know when the loop stops, so will be better to add a variable for maximum number of tries like this. And also you do not need to transform dthe number to string to print it:
num = 0
max_tries = 100
try = 1
guess = 7
while (try < max_tries && num != guess)
num = rand(1..10)
try = try + 1
puts num
end
if (try >= max_tries)
puts "you do not get the guess"
else
puts "over"
end
and you get this:
[4] pry(main)> 9
9
3
4
9
6
9
8
4
5
9
10
4
3
7
over
=> true
Related Topics
Unknown Ruby Interpreter Version (Do Not Know How to Handle): Ruby_Version
Ruby Array to String Conversion
How to Capitalize the First Letter in a String in Ruby
Is Require File.Expand_Path(..., _File_) the Best Practice
Install Latest Stable Version of Ruby Using Rbenv
Rails - Invalid Authenticity Token After Deploy
How to Take Screenshots of Web Pages Using Ruby and a Unix Server
Generate Letters to Represent Number Using Ruby
Ruby Koans: Explicit Scoping on a Class Definition Part 2
Mailer Unable to Access Reset_Token in User Model
What Is Mattr_Accessor in a Rails Module
All Ruby Tests Raising: Undefined Method 'Authenticate' for Nil:Nilclass
Cannot Access Local Sinatra Server from Another Computer on Same Network
Installing the Postgresql Gem with 'Gem Pq' Fails with Error: Failed to Build Gem Native Extension
How to Set Ruby's Load Path Externally