Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random number in a certain range with Ruby?

Tags:

ruby

I am trying to get a random year between 1900 and 1980 with Ruby.

So far I have:

puts 'the year was: ' +  1900.to_s + rand(1980).to_s

but this is just adding 1900 and a random number from 0 - 1979 together to look like 19001947.

I think I'm missing something silly but can anyone shed any light?

like image 709
AndyNico Avatar asked May 15 '11 21:05

AndyNico


2 Answers

Ruby 1.9.3

1.9.3p0 :001 > rand(1900..1980)
 => 1946 
1.9.3p0 :002 > rand(1900..1980)
 => 1929 
1.9.3p0 :003 > rand(1900..1980)
 => 1934 
like image 173
Alex Gusev Avatar answered Sep 27 '22 20:09

Alex Gusev


Give this a try

(1900 + rand(81)).to_s

To be clear for passersby

First, there was an issue regarding string concatenation. The original code in the question was concatenating two strings (containing numbers) together. Example:

"1900" + "1920" = "19001920"

Second, there was an issue the range of random numbers being generated. In this case, since we only want a range of 80 years, we want to use rand(81), instead of rand(1980). We then take that result and add it to the base number, which will give us a random number between 1900 and 1980.

like image 37
Brian Webster Avatar answered Sep 27 '22 20:09

Brian Webster