【问题标题】:Generating random number of length 6 with SecureRandom in Ruby在 Ruby 中使用 SecureRandom 生成长度为 6 的随机数
【发布时间】:2017-05-17 17:20:52
【问题描述】:

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

【问题讨论】:

  • 提示:9**6 是 531441。

标签: ruby ruby-on-rails-5 rspec-rails secure-random


【解决方案1】:

你可以用数学来做:

(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

【讨论】:

  • 谢谢,看来(SecureRandom.random_number(9e5) + 1e5).to_i 就是我要找的。​​span>
  • 如何使用它来生成长度为n的随机数?
  • 请改用9 * 10**(n-1) 10**(n-1)
  • 尝试将9e5 作为参数传递给random_number 时出错,尽管10**6 有效。
  • @MTarantini 你总是可以做到 long_form:1_000_000.
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 你为什么推荐不安全的rand呢?这真是倒退了一步。
    • 是的,我不会使用rand,我会坚持使用SecureRandom
    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2018-01-25
    • 2012-01-26
    • 2020-03-11
    相关资源
    最近更新 更多