Skip to content

Instantly share code, notes, and snippets.

@irisfofs
Last active May 31, 2016 04:38
Show Gist options
  • Save irisfofs/ab32a35bd49ca057134c to your computer and use it in GitHub Desktop.
Save irisfofs/ab32a35bd49ca057134c to your computer and use it in GitHub Desktop.
Ruby snippet to produce discount codes for use in say, Eventbrite.
require "set"
CHARS = []
("0".."9").each { |x| CHARS << x }
("A".."Z").each { |x| CHARS << x }
def create_code(prefix, length)
code = ""
length.times { code << random_character }
"#{prefix}#{code}"
end
def random_character
CHARS[rand(CHARS.length)]
end
# The actual method to call. Just load the file into irb and call this.
# filename - (string) filename to save codes to, such as codes.txt
# number - (int) number of codes to generate
# prefix - (string) a prefix to prepend to every code, like "VENDOR" or "FREE"
# length - (int) number of random characters to append
def create_codes(filename, number, prefix, length)
codes = Set.new
loop do
break if codes.size >= number
codes << create_code(prefix, length)
end
File.open(filename, "w") do |f|
codes.each { f.puts create_code(prefix, length) }
end
end
if __FILE__ == $PROGRAM_NAME
if ARGV.length != 4
puts """Usage:
ruby discount_codes.rb output_filename number_of_codes code_prefix length_of_code
"""
exit
end
create_codes(ARGV[0], ARGV[1].to_i, ARGV[2], ARGV[3].to_i)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment