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

Generating random number of length 6 with SecureRandom in Ruby

我试过 SecureRandom.random_number(9**6) 但有时 returns 5 个数字,有时 6 个数字。我希望它的长度始终为 6。我也更喜欢 SecureRandom.random_number(9**6) 这样的格式,而不使用 6.times.map 这样的语法,这样在我的控制器测试中更容易被打断。

SecureRandom.random_number(n) 给出一个介于 0 到 n 之间的随机值。您可以使用 rand 函数来实现它。

2.3.1 :025 > rand(10**5..10**6-1)
=> 742840

rand(a..b) 给出a和b之间的随机数。在这里,你总是得到一个介于 10^5 和 10^6-1 之间的 6 位随机数。

你可以用数学来计算:

(SecureRandom.random_number(9e5) + 1e5).to_i

然后验证:

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

这会产生 100000..999999 范围内的值:

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

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

def six_digit_rand
  (SecureRandom.random_number(9e5) + 1e5).to_i
end

要生成一个随机的 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')

这里是正在发生的事情的更多细节,通过用解释变量将单行分成多行来显示:

  # 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')