在Ruby中使用SecureRandom生成长度为6的随机数

Jef*_*ong 2 ruby rspec-rails ruby-on-rails-5 secure-random

我尝试过,SecureRandom.random_number(9**6)但有时返回5,有时返回6。我希望它的长度始终为6。我也更喜欢它的格式,SecureRandom.random_number(9**6)而无需使用类似的语法,6.times.map以便在控制器测试中更容易进行打桩。

Eli*_*kes 12

要生成随机的 6 位数字字符串:

# This generates a 6-digit string, where the
# minimum possible value is "000000", and the
# maximum possible value is "999999"
SecureRandom.random_number(10**6).to_s.rjust(6, '0')
Run Code Online (Sandbox Code Playgroud)

以下是所发生情况的更多详细信息,通过将单行分成多行并解释变量来显示:

  # Calculate the upper bound for the random number generator
  # upper_bound = 1,000,000
  upper_bound = 10**6

  # n will be an integer with a minimum possible value of 0,
  # and a maximum possible value of 999,999
  n = SecureRandom.random_number(upper_bound)

  # Convert the integer n to a string
  # unpadded_str will be "0" if n == 0
  # unpadded_str will be "999999" if n == 999999
  unpadded_str = n.to_s

  # Pad the string with leading zeroes if it is less than
  # 6 digits long.
  # "0" would be padded to "000000"
  # "123" would be padded to "000123"
  # "999999" would not be padded, and remains unchanged as "999999"
  padded_str = unpadded_str.rjust(6, '0')
Run Code Online (Sandbox Code Playgroud)


tad*_*man 6

您可以使用数学来做到这一点:

(SecureRandom.random_number(9e5) + 1e5).to_i
Run Code Online (Sandbox Code Playgroud)

然后验证:

100000.times.map do
  (SecureRandom.random_number(9e5) + 1e5).to_i
end.map { |v| v.to_s.length }.uniq
# => [6]
Run Code Online (Sandbox Code Playgroud)

产生的值在100000..999999范围内:

10000000.times.map do
  (SecureRandom.random_number(9e5) + 1e5).to_i
end.minmax
# => [100000, 999999]
Run Code Online (Sandbox Code Playgroud)

如果您需要更简洁的格式,只需将其滚动到方法中:

def six_digit_rand
  (SecureRandom.random_number(9e5) + 1e5).to_i
end
Run Code Online (Sandbox Code Playgroud)