Sanjay Salunkhe
Sanjay Salunkhe

Reputation: 2735

Ruby: how to generate unique alphabetic string in ruby

Is there any in built method in ruby which will generate unique alphabetic string every time(it should not have numbers only alphabets)?

i have tried SecureRandom but it doesn't provide method which will return string containing only alphabets.

Upvotes: 0

Views: 1422

Answers (6)

Touqeer
Touqeer

Reputation: 654

I used Time in miliseconds, than converted it into base 36 which gives me unique aplhanumeric value and since it depends on time so, it will be very unique.

Example: Time.now.to_f.to_s.gsub('.', '').ljust(17, '0').to_i.to_s(36) # => "4j26m4zm2ss"

Take a look at this for full answer: https://stackoverflow.com/a/72738840/7365329

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369478

Is there any in built method in ruby which will generate unique alphabetic string every time(it should not have numbers only alphabets)?

This is not possible. The only way that a string can be unique if you are generating an unlimited number of strings is if the string is infinitely long.

So, it is impossible to generate a string that will be unique every time.

Upvotes: 1

Stefan
Stefan

Reputation: 114188

SecureRandom has a method choose which:

[...] generates a string that randomly draws from a source array of characters.

Unfortunately it's private, but you can call it via send:

SecureRandom.send(:choose, [*'a'..'z'], 8)
#=> "nupvjhjw"

You could also monkey-patch Random::Formatter:

module Random::Formatter
  def alphabetic(n = 16)
    choose([*'a'..'z'], n)
  end
end

SecureRandom.alphabetic
#=> "qfwkgsnzfmyogyya"

Note that the result is totally random and therefore not necessarily unique.

Upvotes: 4

Amadan
Amadan

Reputation: 198378

UUID are designed to have extremely low chance of collision. Since UUID only uses 17 characters, it's easy to change the non-alphabetic characters into unused alphabetic slots.

SecureRandom.uuid.gsub(/[\d-]/) { |x| (x.ord + 58).chr }

Upvotes: 1

dmrlps
dmrlps

Reputation: 70

Try this one

length = 50
Array.new(length) { [*"A".."Z", *"a".."z"].sample }.join
# => bDKvNSySuKomcaDiAlTeOzwLyqagvtjeUkDBKPnUpYEpZUnMGF

Upvotes: -2

Manoj Menon
Manoj Menon

Reputation: 1038

def get_random_string(length=2)
  source=("a".."z").to_a + ("A".."Z").to_a
  key=""
  length.times{ key += source[rand(source.size)].to_s }
  key
end

How about something like this if you like some monkey-patching, i have set length 2 here , please feel free to change it as per your needs

get_random_string(7)

Upvotes: 0

Related Questions