如何在 Ruby 中获取随机数

发布于 2024-07-08 06:49:13 字数 51 浏览 6 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

┼── 2024-07-15 06:49:13

使用 rand(range)

来自 Ruby 随机数:

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

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


正如 Marc-André Lafortune他的答案如下(投票赞成)Ruby 1.9.2 有自己的 Random (Marc-André 本人帮助调试,因此<该功能的 href="http://redmine.ruby-lang.org/versions/show/11" rel="noreferrer">1.9.2 目标)。

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

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

注意:

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

Use rand(range)

From Ruby Random Numbers:

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 rand with no arguments.


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

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]

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.

懒猫 2024-07-15 06:49:13

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

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

Available for all versions of Ruby by require my 向后移植 gem。

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

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

Random 类本身充当随机生成器,因此你直接调用:

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

关于Random.new的注释

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

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

Random.new 有用的情况如下:

  • 您正在编写一个 gem,并且不想干扰 rand/Random.rand 的序列 主程序可能依赖于
  • 您想要单独的可重现的随机数序列(例如每个线程一个)
  • 您希望能够保存和恢复可重现的随机数序列(简单如Random对象可以编组)

While you can use rand(42-10) + 10 to get a random number between 10 and 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(10...42) # => 13

Available for all versions of Ruby by requiring my backports gem.

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

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

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

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

Notes on Random.new

In most cases, the simplest is to use rand or 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.

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

The cases where Random.new is helpful are the following:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that 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 Random objects can marshalled)
感情旳空白 2024-07-15 06:49:13

如果您不仅要寻找数字,还要寻找十六进制或 uuid,值得一提的是,SecureRandom 模块在 1.9.2+ 中找到了从 ActiveSupport 到 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"

它记录在此处: Ruby 1.9.3 - 模块:安全随机 (lib/securerandom.rb)

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

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)

娜些时光,永不杰束 2024-07-15 06:49:13

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

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

You can generate a random number with the rand method. The argument passed to the rand method should be an integer or a range, and returns a corresponding random number within the 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
原来分手还会想你 2024-07-15 06:49:13

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

rand(n + 1)

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

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

rand(n + 1)

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

心凉 2024-07-15 06:49:13

那这个呢?

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

What about this?

n = 3
(0..n).to_a.sample
终陌 2024-07-15 06:49:13

对问题的最简单回答:

rand(0..n)

Simplest answer to the question:

rand(0..n)
飘逸的'云 2024-07-15 06:49:13

您只需使用random_number即可。

如果 n 为正整数,random_number 返回一个整数:0 <= random_number < 名词

像这样使用它:

any_number = SecureRandom.random_number(100) 

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

You can simply use random_number.

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

Use it like this:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.

岁月苍老的讽刺 2024-07-15 06:49:13
rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

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

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.

辞旧 2024-07-15 06:49:13

range = 10..50

rand(range)

range.to_a.sample

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

range = 10..50

rand(range)

or

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)

旧时模样 2024-07-15 06:49:13

你可以做兰特(范围)

x = rand(1..5)

you can do rand(range)

x = rand(1..5)
路还长,别太狂 2024-07-15 06:49:13

此链接对此会有帮助;

http://ruby-doc.org/core-1.9.3/Random.html

下面对 ruby​​ 中的随机数有一些更清晰的说明;

生成 0 到 10 之间的整数

puts (rand() * 10).to_i

生成 0 到 10 之间的数字
以更易读的方式

puts rand(10)

生成 10 到 15 之间的数字
包括15个

puts rand(10..15)

非随机的随机数

每次生成相同的数字序列
程序运行

srand(5)

生成10个随机数

puts (0..10).map{rand(0..10)}

This link is going to be helpful regarding this;

http://ruby-doc.org/core-1.9.3/Random.html

And some more clarity below over the random numbers in ruby;

Generate an integer from 0 to 10

puts (rand() * 10).to_i

Generate a number from 0 to 10
In a more readable way

puts rand(10)

Generate a number from 10 to 15
Including 15

puts rand(10..15)

Non-Random Random Numbers

Generate the same sequence of numbers every time
the program is run

srand(5)

Generate 10 random numbers

puts (0..10).map{rand(0..10)}
如梦 2024-07-15 06:49:13

在 ruby​​ 中获取随机数的简单方法是,

def random    
  (1..10).to_a.sample.to_s
end

Easy way to get random number in ruby is,

def random    
  (1..10).to_a.sample.to_s
end
暗藏城府 2024-07-15 06:49:13

也许它对你有帮助。 我在我的应用程序中使用它

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github .com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

它对我来说效果很好

Maybe it help you. I use this in my app

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

It works fine for me

暮凉 2024-07-15 06:49:13

这个怎么样?

num = Random.new
num.rand(1..n)

How about this one?

num = Random.new
num.rand(1..n)
楠木可依 2024-07-15 06:49:13

不要忘记首先使用 srand() 为 RNG 播种。

Don't forget to seed the RNG with srand() first.

時窥 2024-07-15 06:49:13

尝试使用 array#shuffle 方法进行随机化

array = (1..10).to_a
array.shuffle.first

Try array#shuffle method for randomization

array = (1..10).to_a
array.shuffle.first
撩起发的微风 2024-07-15 06:49:13

您可以使用 ruby​​ rand 方法来实现此目的,如下所示:

rand(n+1)

您需要使用 n+ 1 因为 rand 方法返回任何大于或等于 0 但小于传递的参数值的随机数。

You can use ruby rand method for this like below:

rand(n+1)

You need to use n+1 as the rand method returns any random number greater than or equal to 0 but less than the passed parameter value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文