如何在Ruby中获得随机数 [英] How to get a random number in Ruby

查看:186
本文介绍了如何在Ruby中获得随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 with 2 + rand(6) + rand(6).

最后,如果您只需要一个随机浮点数,只需调用不带任何参数的rand.

Finally, if you just need a random float, just call rand with no arguments.


Marc-AndréLafortune 所述/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866>他在下面的回答(投票),有助于调试,因此该功能的目标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)通常不是一个好主意,正如他的答案(再次).

  • Using Random.new.rand(20..30) (using Random.new) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).

但是,如果您不使用Random.new,则 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)返回一个大于或等于0且小于自变量的随机整数". 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆