如何在Ruby中获取随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/198460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:44:44  来源:igfitidea点击:

How to get a random number in Ruby

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4random

提问by Mark A. Nicolosi

How do I generate a random number between 0and n?

如何在0和之间生成随机数n

回答by VonC

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). A roll in craps could be simulated with 2 + rand(6) + rand(6).

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

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

最后,如果您只需要一个随机浮点数,只需rand不带参数调用即可。



As Marc-André Lafortunementions in his answer below (go upvote it), Ruby 1.9.2 has its own Randomclass(that Marc-André himself helped to debug, hence the 1.9.2 targetfor 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..30includes 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)回报“的随机整数大于或等于零且小于参数。” 20..30包括 30,我需要想出一个 0 到 11 之间的随机数,不包括 11。

回答by Marc-André Lafortune

While you can use rand(42-10) + 10to get a random number between 10and 42(where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:

虽然您可以使用和rand(42-10) + 10之间的随机数(其中包括 10 和不包括 42),但自 Ruby 1.9.3 以来有更好的方法,您可以在其中调用:1042

rand(10...42) # => 13

Available for all versions of Ruby by requiring my backportsgem.

通过需要我的backportsgem,可用于所有版本的 Ruby 。

Ruby 1.9.2 also introduced the Randomclass so you can create your own random number generator objects and has a nice API:

Ruby 1.9.2 还引入了Random该类,因此您可以创建自己的随机数生成器对象,并有一个不错的 API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

The Randomclass itself acts as a random generator, so you call directly:

Random类本身作为一个随机数生成器,让您直接拨打:

Random.rand(10...42) # => same as rand(10...42)

Notes on Random.new

注意事项 Random.new

In most cases, the simplest is to use randor Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

在大多数情况下,最简单的方法是使用randRandom.rand。每次您想要一个随机数时都创建一个新的随机生成器是一个非常糟糕的主意。如果您这样做,您将获得初始种子算法的随机属性,与随机生成器本身的属性相比,这是非常糟糕的。

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.newand use it everywhere else.

如果你使用Random.new,你应该尽可能少地调用它,例如一次,MyApp::Random = Random.new并在其他地方使用它。

The cases where Random.newis helpful are the following:

其中,这些案件Random.new是有帮助的有以下几种:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.randthat the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Randomobjects can marshalled)
  • 您正在编写一个 gem 并且不想干扰主程序可能依赖的rand/的顺序Random.rand
  • 你想要单独的可重复随机数序列(比如每个线程一个)
  • 您希望能够保存和恢复可重复的随机数序列(就像Random对象可以编组一样简单)

回答by Thomas Fankhauser

If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandommodule found its way from ActiveSupportto the ruby core in 1.9.2+. So without the need for a full blown framework:

如果您不仅要寻找数字,还要寻找十六进制或 uuid,那么值得一提的是,该SecureRandom模块ActiveSupport在 1.9.2+ 中找到了从ruby 核心的方式。所以不需要一个完整的框架:

require 'securerandom'

p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88

p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409

p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)

它记录在这里:Ruby 1.9.3 - 模块:SecureRandom (lib/securerandom.rb)

回答by Thomas Fankhauser

You can generate a random number with the randmethod. The argument passed to the randmethod should be an integeror a range, and returns a corresponding random number within the range:

您可以使用该rand方法生成一个随机数。传递给该rand方法的参数应该是 aninteger或 a range,并返回范围内的相应随机数:

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

回答by Mark A. Nicolosi

Well, I figured it out. Apparently there is a builtin (?) function called rand:

嗯,我想通了。显然有一个名为 rand 的内置 (?) 函数:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.

如果有人给出更详细的答案,我会将其标记为正确答案。

回答by Rimian

What about this?

那这个呢?

n = 3
(0..n).to_a.sample

回答by sqrcompass

Simplest answer to the question:

最简单的问题答案:

rand(0..n)

回答by techdreams

You can simply use random_number.

您可以简单地使用random_number.

If a positive integer is given as n, random_numberreturns an integer: 0 <= random_number< n.

如果一个正整数被指定为 n,则random_number返回一个整数:0 <= random_number< n。

Use it like this:

像这样使用它:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.

输出将是 0 到 100 之间的任何数字。

回答by Josh

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

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.

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

回答by sumit

range = 10..50

范围 = 10..50

rand(range)

兰特(范围)

or

或者

range.to_a.sample

range.to_a.sample

or

或者

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)

range.to_a.shuffle(这将打乱整个数组,您可以通过第一个或最后一个随机数或从该数组中选择一个随机数来选择随机数)