如何在Ruby中获取随机数 [英] How to get a random number in Ruby
问题描述
如何在 0
和 n
之间生成一个随机数?
How do I generate a random number between 0
and n
?
推荐答案
使用 rand(range)
来自 Ruby 随机数:
如果您需要一个随机整数来模拟一卷六面骰子,您可以使用:1 + rand(6)
.掷骰子可以用 2 + rand(6) + rand(6)
模拟.
If you needed a random integer to simulate a roll of a six-sided die, you'd use:
1 + rand(6)
. A roll in craps could be simulated with2 + rand(6) + rand(6)
.
最后,如果你只需要一个随机浮点数,只需调用 rand
不带参数.
Finally, if you just need a random float, just call rand
with no arguments.
<小时>
正如 Marc-André Lafortune 在 他在下面的回答(点赞),Ruby 1.9.2 有自己的Random
代码> 类(Marc-André 本人帮助调试,因此,该功能的 1.9.2 目标).
As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random
class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).
例如,在这个游戏中,您需要猜10个数字,你可以用:
For instance, in this game where you need to guess 10 numbers, you can initialize them with:
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
注意:
使用
Random.new.rand(20..30)
(使用Random.new
)通常不是一个好主意,详细解释(再次)由 Marc-André Lafortune,在 他的回答(再次).
Using
Random.new.rand(20..30)
(usingRandom.new
) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).
但是如果你不使用 Random.new
,那么 类方法 rand
只需要一个 max
值,而不是 Range
,因为栏杆(充满活力地)在评论中指出(并且如Random
的文档).只有 实例方法 可以采用 Range
,如用7生成随机数所示数字.
But if you don't use Random.new
, then the class method rand
only takes a max
value, not a Range
, as banister (energetically) points out in the comment (and as documented in the docs for Random
). Only the instance method can take a Range
, as illustrated by generate a random number with 7 digits.
这就是为什么 Random.new.rand(20..30)
的等价物是 20 + Random.rand(11)
,因为 Random.rand(int)
返回大于或等于零且小于参数的随机整数."20..30
包括 30,我需要在 0 到 11 之间找出一个随机数,不包括 11.
This is why the equivalent of Random.new.rand(20..30)
would be 20 + Random.rand(11)
, since Random.rand(int)
returns "a random integer greater than or equal to zero and less than the argument." 20..30
includes 30, I need to come up with a random number between 0 and 11, excluding 11.
这篇关于如何在Ruby中获取随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!