如何生成介于0和n之间的随机数?
当前回答
这个怎么样?
num = Random.new
num.rand(1..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
这对我来说很好
如果您不仅要寻找数字,还要寻找十六进制或uuid,那么值得一提的是,SecureRandom模块在1.9.2+中找到了从ActiveSupport到ruby内核的方法。因此,不需要完整的框架:
require 'securerandom'
p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88
p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409
p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
它记录在这里:Ruby1.9.3-模块:SecureRandom(lib/SecureRandom.rb)
您可以使用ruby rand方法,如下所示:
rand(n+1)
您需要使用n+1,因为rand方法返回任何大于或等于0但小于传递的参数值的随机数。
可以使用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
嗯,我想通了。显然有一个内置(?)函数叫做rand:
rand(n + 1)
如果有人回答了更详细的答案,我会将其标记为正确答案。
推荐文章
- 确定ActiveRecord对象是否为New
- Rails中的OO设计:在哪里放置东西
- 如何在Heroku上重新启动rails服务器?
- respond_to块如何工作?
- 给定一个类,查看实例是否有方法(Ruby)
- rails局部模板中的可选局部变量:如何退出(defined?foo)混乱?
- 在日历应用程序中建模重复事件的最佳方法是什么?
- Ruby Bundle Symbol not found: _SSLv2_client_method (LoadError)
- 如何在c++中生成一个随机数?
- 如何创建一个私有类方法?
- rails耙任务是否提供对ActiveRecord模型的访问?
- 无法安装pg gem
- 双* (splat)操作符做什么
- 如何使用Ruby on Rails进行HTTP请求?
- (1) libcurl不支持或禁用https协议