开发者

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 w开发者_运维百科ith 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.


puts "The year was #{1900 + rand 81}"


Yes: you're getting the "string catenation" overload of +. Try (1900+rand(80)).to_s


Ruby 1.8+

(1900..1980).to_a[rand(80)]
# or little more Rubyistic
(1900..1980).to_a.shuffle.first

Ruby 1.9+

[*1900..1980].sample
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜