Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

ruby-on-rails - 如何在Ruby中获得随机数(How to get a random number in Ruby)

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

  ask by Mark A. Nicolosi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use rand(range)

(使用rand(range))

From Ruby Random Numbers :

(从Ruby随机数开始 :)

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6) .

(如果您需要一个随机整数来模拟六面骰子的掷骰,则可以使用: 1 + rand(6) 。)

A roll in craps could be simulated with 2 + rand(6) + rand(6) .

(掷骰子可以用2 + rand(6) + rand(6)模拟。)

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

(最后,如果您只需要随机浮点数,则可以不带任何参数调用rand 。)


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).

(正如Marc-AndréLafortune下面的回答中提到的(支持它)Ruby 1.9.2具有自己的Random (Marc-André自己进行了调试 ,因此该功能的目标1.9.2 )。)

For instance, in this game where you need to guess 10 numbers , you can initialize them with:

(例如,在这个游戏中,您需要猜测10个数字 ,可以使用以下方法初始化它们:)

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

(注意:)

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.

(这就是为什么Random.new.rand(20..30)等于20 + Random.rand(11) ,因为Random.rand(int)返回“一个大于或等于0且小于 0的随机整数。 自变量 。” 20..30包括30,我需要给出一个介于0到11之间的随机数(不包括11)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...