Generate unique random alphanumeric strings ruby

There are many ways to achieve the same, after meddling with different ways and from the help of few ruby clans, I could decide upon the most reliable and the best way to achieve this as below.

Given a length 'len', here its 6 generate a series of unique random strings. Makes use of rand() with max value as 36^@len -1
As [a-z] and [0-9] makes 36 chars and to_s(base=10) along with a simple right justification rjust()

From docs :

rand(max=0) => number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.


fix.to_s( base=10 ) → aString

Returns a string containing the representation of fix radix base (between 2 and 36).


str.rjust(integer, padstr=' ') => new_str

If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str.

class RandomGenerate
  attr_reader :generated
  def initialize(len)
    @len = len
    @generated = []
  def get
      rstr = rand(36 ** @len - 1).to_s(36).rjust(@len, "0")
    end while @generated.member? rstr
    @generated << rstr
if $0 == __FILE__
  rand_string =
  10.times do
    puts rand_string.get
  p rand_string.generated

Share this