如何生成介于0和n之间的随机数?


当前回答

别忘了先用srand()为RNG种子。

其他回答

这个怎么样?

num = Random.new
num.rand(1..n)
rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

请注意,范围选项仅在更新(我相信是1.9+)的ruby版本中可用。

尝试array#shuffle方法进行随机化

array = (1..10).to_a
array.shuffle.first

可以使用rand方法生成随机数。传递给rand方法的参数应为整数或范围,并返回范围内的相应随机数:

rand(9)       # this generates a number between 0 to 8
rand(0 .. 9)  # this generates a number between 0 to 9
rand(1 .. 50) # this generates a number between 1 to 50
#rand(m .. n) # m is the start of the number range, n is the end of number range

别忘了先用srand()为RNG种子。