如何生成介于0和n之间的随机数?
当前回答
如果您不仅要寻找数字,还要寻找十六进制或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)
其他回答
嗯,我想通了。显然有一个内置(?)函数叫做rand:
rand(n + 1)
如果有人回答了更详细的答案,我会将其标记为正确答案。
范围=10..50
兰特(范围)
or
采样范围
or
range.to_a.shuffle(这将对整个数组进行随机排序,您可以从这个数组中按第一个或最后一个或任意一个选择随机数)
也许这对你有帮助。我在应用程序中使用此功能
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(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版本中可用。
您可以使用ruby rand方法,如下所示:
rand(n+1)
您需要使用n+1,因为rand方法返回任何大于或等于0但小于传递的参数值的随机数。
推荐文章
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Rails:如何在Rails 4中引用CSS中的图像
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- Rails -嵌套包括活动记录?
- random.seed():它做什么?
- 在Gem::Specification.reset期间未解决的规格:
- Delete_all vs destroy_all
- 双引号vs单引号
- 用any可以吗?'来检查数组是否为空?
- Rails获取“each”循环的索引
- Java中生成UUID字符串的有效方法(UUID. randomuuid ().toString()不带破折号)
- Ruby类实例变量与类变量
- 如何从字典中获得一个随机值?