AndyNico AndyNico - 1 year ago 65
Ruby Question

How do I generate a random number in a certain range with 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download