![]() |
| ||
| This is a simple, but complete (pseudo) random password generator. Examples of usage: $ ruby pgen.rb For complete usage guidelines, run $ ruby pgen.rb --helpThis (hopefully) serves as both a useful program, and a simple example of the use of the optparse module. EDIT:Code fixed to correct error. Everything should be working now. ![]() |
# pgen.rb # by Jesse H-K on Thursday, June 15 2006 require 'optparse' class Array def random_choice self[rand(self.length)] end end def parse_options(args) options = {} options[:length] = 10 opts = OptionParser.new do |opts| opts.banner = "Usage: pgen.rb [options]" opts.on("-n", "--numbers", "Include the digits [0-9] in the password.") do |n| options[:numb] = n end opts.on("-p", "--punctuation", "Include common punctuation characters in the password.") do |p| options[:punct] = p end opts.on("-u", "--uppercase", "Include uppercase letters in the password.") do |u| options[:upcase] = u end opts.on("-l", "--length=[LENGTH]", Integer, "The length of the password. Default is 10 characters.") do |l| options[:length] = l end end opts.parse! options end class PasswordGenerator @@options = { :numb => ('0'..'9').to_a, :punct => %w(. , ! ? @ & :), :upcase => ('A'..'Z').to_a } def initialize(length, *opts) @possible = *('a'..'z') @length = length parse_content_options(opts) end def parse_content_options(opts) opts.each { |opt| @possible.concat(@@options[opt]) if @@options.key? opt } end def generate (1..@length).inject("") { |passwd, e| passwd << @possible.random_choice } end private :parse_content_options end options = parse_options(ARGV) puts PasswordGenerator.new(options[:length], *options.keys).generate