3

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
sawa
  • 160,959
  • 41
  • 265
  • 366
gr8scott06
  • 833
  • 11
  • 19

5 Answers5

16
Array.new(n){[*"A".."Z", *"0".."9"].sample}.join
sawa
  • 160,959
  • 41
  • 265
  • 366
3

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)
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Matheus Porto
  • 149
  • 1
  • 5
1

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.)

Cary Swoveland
  • 101,330
  • 6
  • 60
  • 95
0

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
Mario Ruiz
  • 52
  • 6
0

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

Gaurav Patil
  • 734
  • 8
  • 19