anti-k anti-k - 1 year ago 109
Ruby Question

Generating special secure id

I have to generate a unique reference in the format similar to ABC-4F-ABC-8D-ABC (where: ABC is random 3-char string, 4F, 8D are random hex numbers).
I am a new guy to ruby, so please forgive me if this is duplicate(did not found smth that is similar so far). How can I do this?

Answer Source

Everything you need is built into Ruby.

You can create an array that is your alphabet and then pick samples from it to form your string:

ALPHA = ('A'..'Z').to_a # might also want to add numbers or lower-case letters?
HEX = ('A'..'F').to_a + (0..9).to_a

def generate_string(alphabet, length)
  # pick random elements from the alphabet and concatenate 
  # until length is reached.
  # key method is `sample` which selects a random element from 
  # an array (the alphabet, in your case)
  # you can try it on irb like so:
  # [1, 2, 3].sample

Then you can do something like:

def generate_unique_reference
  "#{generate_string(ALPHA, 3)}-#{generate_string(HEX, 2)}-....."

I'll leave it to you to complete the exercise (sounds like homework, no?)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download