---
title: "Generate Unique Random Alphanumeric Strings Ruby"
description: "There are many ways to achieve the same, after meddling with different ways and from the help of few ruby clans, I could."
url: "https://h3manth.com/scribe/generate-unique-random-alphanumeric-strings-ruby/"
canonical_url: "https://h3manth.com/scribe/generate-unique-random-alphanumeric-strings-ruby/"
markdown_url: "https://h3manth.com/scribe/blog/generate-unique-random-alphanumeric-strings-ruby.md"
publishDate: "2010-03-31T00:00:00.000Z"
author: "Hemanth HM"
category: "linux"
tags: ["ruby","linux"]
word_count: 261
reading_time_minutes: 2
x_markdown_tokens: 516
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

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

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.

**Logic:** 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.

to_s()

fix.to_s( base=10 ) → aString

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

rjust()

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 = []
    

end

def get
    
    
    begin
      rstr = rand(36 ** @len - 1).to_s(36).rjust(@len, "0")
    end while @generated.member? rstr
    
    @generated << rstr
    
    rstr
    

end end

if $0 == **FILE** rand_string = UniqueGenerator.new(6)

10.times do
    
    
    puts rand_string.get
    

end

p rand_string.generated end
