2014-01-05

One of my tasks at work was to write a script to process a large number of codes. However, when I needed to write the processing script, the codes did not yet exists. What I did know, was that the codes would be text strings, and to get my job done I really just needed a bunch of made up test data that consisted of text strings.

After a few minutes in my favorite text editor, I had a quick and dirty Ruby script that would generate a number of codes for me, and this would allow me to get cracking on the script that would process the codes.

Enter the Ruby

#!/usr/bin/env ruby

#how many codes do we need to generate?
num_codes ARGV[0].to_i
num_codes 100 if num_codes.zero?

#what characters are valid for a code?
@chars %w{a b c d e f g 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J K L M N P Q}

#function to create a new code
def make_code
  #start with a empty string
  code ''
  #loop 10 times
  (1..10).each do
    #add a random valid character to to the 'code' string
    code << @chars.sample
  end
  return code
end

#start with an empty list of codes
@codes = []

#loop to the number of codes we need to generate
(1..num_codes).each do |i|
  #make a code
  code make_code
  #does this code already exist? if so, it is not unique
  while @codes.include?(codedo
    #make another code
    code make_code
  end
  #add the code to the codes list
  @codes << code
  #print the code
  puts code
end

For easier copy/paste, this script is also available at: http://hoof.jezra.net/snip/oi

OK, Time Out: go look at the list of valid code characters. There are a few things that I don't like doing when generating codes....

  • mixing case: if at any time, someone needs to read the code to someone else, DO NOT MIX CASE.
  • using both lower case 'L' and number 1 as valid characters: they are far too easy to confuse
  • using capital "O" and number 0 as valid characters: again, they are easy to confuse.

Alright, back to the code....
When I refer to the script as quick and dirty, I mean that the script is written quickly and not written for efficiency. There are certainly some ways to make this script faster, but for what I needed, the script works just fine.

Comments
Name:
not required
Email:
not required (will not be displayed)
Website:
not required (will link your name to your site)
Comment:
required
Please do not post HTML code or bbcode unless you want it to show up as code in your post. (or if you are a blog spammer, in which case, you probably aren't reading this anyway).
Prove you are human by solving a math problem! I'm sorry, but due to an increase of blog spam, I've had to implement a CAPTCHA.
Problem:
6 minus 0
Answer:
required
subscribe
 
2016
2015
2014
2013
2012
2011
2010
December
November
October
September
August
July
June
May
April
March
February
January
2009
December
November
October
September
August
July
June
May
April
March
February
January
2008