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


当前回答

此链接将对此有所帮助;

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

下面对红宝石中的随机数进行了更清晰的描述;

生成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)}

其他回答

范围=10..50

兰特(范围)

or

采样范围

or

range.to_a.shuffle(这将对整个数组进行随机排序,您可以从这个数组中按第一个或最后一个或任意一个选择随机数)

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

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

此链接将对此有所帮助;

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

下面对红宝石中的随机数进行了更清晰的描述;

生成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)}

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

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

这对我来说很好

您可以简单地使用random_number。

如果给定正整数为n,random_number返回一个整数:0<=random_nnumber<n。

这样使用:

any_number = SecureRandom.random_number(100) 

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