rubyruby-on-rails-5rspec-railssecure-random

Generating random number of length 6 with SecureRandom in Ruby


I tried SecureRandom.random_number(9**6) but it sometimes returns 5 and sometimes 6 numbers. I'd want it to be a length of 6 consistently. I would also prefer it in the format like SecureRandom.random_number(9**6) without using syntax like 6.times.map so that it's easier to be stubbed in my controller test.


Solution

  • You can do it with math:

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

    Then verify:

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

    This produces values in the range 100000..999999:

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

    If you need this in a more concise format, just roll it into a method:

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