如何在Ruby中获取随机数

830

我该如何生成一个介于0n之间的随机数?


1
在编写 rand 代码之前使用 srand <some_number> 将会给你一个确定性的(即可重复的)伪随机序列,如果你需要的话。https://ruby-doc.org/core-2.5.6/Random.html#method-c-srand - Purplejacket
18个回答

5

你可以使用 rand(range) 函数。

x = rand(1..5)

4
这个链接对于这个问题会非常有帮助; 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)}

你也可以关注这个博客,了解有关 Ruby 中随机数的逐步详细图片说明;http://www.sitepoint.com/tour-random-ruby/ - Sam

4

在Ruby中获取随机数的简单方法是:

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

2
也许这会对你有所帮助。我在我的应用程序中使用了这个。
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
这里是RubyWorks的一个开源项目,可以生成随机字符串。根据我的测试,它的功能非常完善。

2
这个怎么样?
num = Random.new
num.rand(1..n)

1
尝试使用array#shuffle方法进行随机化。
array = (1..10).to_a
array.shuffle.first

1
如果你必须创建一个完整的数组,至少要用.sample替换.shuffle.first - Camille Goudeseune

1
不要忘记先用 srand() 种下随机数生成器的种子。

2
如果你不调用srand()函数会发生什么? - Alex B
21
如果还没有调用,则使用当前时间作为种子自动调用srand。 - Julian H

0

您可以像下面这样使用 Ruby rand 方法:

rand(n+1)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接