如何生成介于0和n之间的随机数?
当前回答
问题的最简单答案:
rand(0..n)
其他回答
也许这对你有帮助。我在应用程序中使用此功能
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
这对我来说很好
此链接将对此有所帮助;
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)}
嗯,我想通了。显然有一个内置(?)函数叫做rand:
rand(n + 1)
如果有人回答了更详细的答案,我会将其标记为正确答案。
你可以做rand(范围)
x = rand(1..5)
可以使用rand方法生成随机数。传递给rand方法的参数应为整数或范围,并返回范围内的相应随机数:
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
推荐文章
- 理解:Rails的has_one/has_many的源选项
- 使用该集合的原因。种子功能
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 从枚举中选择一个随机值?
- 什么时候使用Struct vs. OpenStruct?
- 我如何在c++中创建一个随机的字母数字字符串?