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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With