4

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

4

3 回答 3

11

你可以用数学来做:

(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
于 2017-05-17T19:29:35.857 回答
6

要生成随机的 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')
于 2019-06-12T14:06:51.120 回答
-1

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 位随机数。

于 2017-05-17T17:32:18.117 回答