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
0

5 Answers 5

18
Array.new(n){[*"A".."Z", *"0".."9"].sample}.join
Sign up to request clarification or add additional context in comments.

3 Comments

curiosity, any reason to do .sample over [rand(36)] ?
I can think of a couple: sample is more elegant, and it needn't be changed if the array being sampled is changed in size.
Curiosity, any reason to do [rand(36)] over sample?
5

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)

Comments

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

1 Comment

You should do [*'A'..'Z', *"0".."9"].sample(10).join otherwise you will have a mixture between strings and ints...
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.)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.