我该如何生成一个介于0
和n
之间的随机数?
我该如何生成一个介于0
和n
之间的随机数?
你可以使用 rand(range) 函数。
x = rand(1..5)
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中获取随机数的简单方法是:
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
这里是RubyWorks的一个开源项目,可以生成随机字符串。根据我的测试,它的功能非常完善。num = Random.new
num.rand(1..n)
array#shuffle
方法进行随机化。array = (1..10).to_a
array.shuffle.first
.sample
替换.shuffle.first
! - Camille Goudeseune
rand
代码之前使用srand <some_number>
将会给你一个确定性的(即可重复的)伪随机序列,如果你需要的话。https://ruby-doc.org/core-2.5.6/Random.html#method-c-srand - Purplejacket