4

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
  • 165,429
  • 45
  • 277
  • 381
gr8scott06
  • 903
  • 1
  • 11
  • 20

5 Answers5

17
Array.new(n){[*"A".."Z", *"0".."9"].sample}.join
sawa
  • 165,429
  • 45
  • 277
  • 381
4

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Matheus Porto
  • 169
  • 1
  • 5
2

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
  • 1,162
  • 10
  • 20
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
  • 106,649
  • 6
  • 63
  • 100
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
  • 72
  • 7