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


当前回答

您可以使用ruby rand方法,如下所示:

rand(n+1)

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

其他回答

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

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

也许这对你有帮助。我在应用程序中使用此功能

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

这对我来说很好

问题的最简单答案:

rand(0..n)

虽然您可以使用rand(42-10)+10来获得10到42之间的随机数(其中10是包含的,42是不包含的),但自Ruby 1.9.3以来,有一种更好的方法,您可以调用:

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

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

Ruby1.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或Random.rand。每次你想要一个随机数时,创建一个新的随机生成器是一个非常糟糕的主意。如果您这样做,您将获得初始种子算法的随机财产,与随机生成器本身的财产相比,这些属性非常糟糕。

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

Random.new有帮助的情况如下:

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

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版本中可用。