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


当前回答

你可以做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

你可以做rand(范围)

x = rand(1..5)

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

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

您可以简单地使用random_number。

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

这样使用:

any_number = SecureRandom.random_number(100) 

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

如果您不仅要寻找数字,还要寻找十六进制或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)