Safe hexadecimal digits only

Trying to generate random numbers with the SecureRandom class of rails. Can we create a random number with SecureRandom.hex that contains only numbers and alphabets.

For instance:

Instead

SecureRandom.hex(4)
=> "95bf7267"

He must give

SecureRandom.hex(4)
=> "95237267"
+5
source share
3 answers

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

I believe that you are looking for another method: #random_number.

SecureRandom.random_number(a_big_number)

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

For basic use cases, just use #rand.

rand(9999)

Edited by:

, , , . :

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

#rand_by_length . String # center . #rand . .

+8

, ( c charlie).

length = 20
id = (SecureRandom.random_number * (10**length)).round.to_s # => "98075825200269950976"

id.split(//).each_slice(4).to_a.map(&:join).join('-') # => "9807-5825-2002-6995-0976"
+1
length = 4

[*'0'..'9'].sample(length).join

so simple:)

+1
source

All Articles