swap.nil swap.nil - 1 year ago 115
Ruby Question

Secure Random hex digits only

Trying to generate random digits with SecureRandom class of rails. Can we create a random number with SecureRandom.hex which includes only digits and no alphabets.

For example:

Instead of

=> "95bf7267"

It should give

=> "95237267"

Answer Source

Check out the api for SecureRandom: http://rails.rubyonrails.org/classes/ActiveSupport/SecureRandom.html

I believe you're looking for a different method: #random_number.


Since #hex returns a hexadecimal number, it would be unusual to ask for a random result that contained only numerical characters.

For basic use cases, it's simple enough to use #rand.



I'm not aware of a library that generates a random number of specified length, but it seems simple enough to write one. Here's my pass at it:

def rand_by_length(length)
  rand((9.to_s * length).to_i).to_s.center(length, rand(9).to_s).to_i

The method #rand_by_length takes an integer specifying length as a param and tries to generate a random number of max digits based on the length. String#center is used to pad the missing numbers with random number characters. Worst case calls #rand for each digit of specified length. That may serve your need.