如何在 Ruby 中获取随机数 [英] How to get a random number in Ruby
问题描述
如何在0
和n
之间生成一个随机数?
How do I generate a random number between 0
and n
?
推荐答案
来自 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
class(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
,如banister(积极地)在评论中指出(并在 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屋!