How can I generate an n-character pseudo random string containing only A-Z
, 0-9
like SecureRandom.base64 without "+"
, "/"
, and "="
? For example:
(0..n).map {(('1'..'9').to_a + ('A'..'Z').to_a)[rand(36)]}.join
How can I generate an n-character pseudo random string containing only A-Z
, 0-9
like SecureRandom.base64 without "+"
, "/"
, and "="
? For example:
(0..n).map {(('1'..'9').to_a + ('A'..'Z').to_a)[rand(36)]}.join
Array.new(n){[*"A".."Z", *"0".."9"].sample}.join
An elegant way to do it in Rails 5 (I don't test it in another Rails versions):
SecureRandom.urlsafe_base64(n)
where n
is the number of digits that you want.
ps: SecureRandom
uses a array to mount your alphanumeric string, so keep in mind that n
should be the amount of digits that you want + 1.
ex: if you want a 8 digit alphanumeric:
SecureRandom.urlsafe_base64(9)
You can do simply like below:
[*'A'..'Z', *0..9].sample(10).join
Change the number 10 to any number to change the length of string
Even brute force is pretty easy:
n = 20
c = [*?A..?Z + *?0..?9]
size = c.size
n.times.map { c[rand(size)] }.join
#=> "IE210UOTDSJDKM67XCG1"
or, without replacement:
c.sample(n).join
#=> "GN5ZC0HFDCO2G5M47VYW"
should that be desired. (I originally had c = [*(?A..?Z)] + [*(?0..?9)]
, but saw from @sawa's answer that that could be simplified quite a bit.)
To generate a random string from 10 to 20 characters including just from A to Z and numbers, both always:
require 'string_pattern'
puts "10-20:/XN/".gen