From: "Perl J." Date: 2011-09-26T08:08:21+09:00 Subject: Re: Looking for better/familiar approach to command line opts Wow, time being what it is, I just need to post to a forum sooner. :-) It never fails that when I post to a forum asking for help, immediately thereafter I figure it out. It turns out that the original code I posted in Ruby... WORKED. Exactly as I wanted it to. I was just making a stupid, dumb rookie mistake. This is exactly what I want. Now there might be a better way to do it, but this produces the results I want: require "optparse" class Options attr_reader :args, :cmdline, :options_list def initialize( options ) @cmdline = ARGV.join( ' ' ) @options_list = options.values.join params = ARGV.getopts( @options_list ) options.each do |key,value| value.sub!( /:/, '' ) self.class.send( :define_method, key ) { params[value] } end @args = Array.new( ARGV ) end end options = Options.new({ :source_path => 's:', :dest_path => 'd:', :verbose => 'v', }) puts "Source path.......: #{options.source_path}" puts "Destination path..: #{options.dest_path}" puts "Verbose is........: #{options.verbose ? 'ON' : 'OFF'}" puts "Command line was..: #{options.cmdline}" puts "Arguments.........: #{options.args.join( ' ' )}" puts "getopts() list....: #{options.options_list}" Returns: pj@matrix-dhcp-191:~/Work/Clients/Nunya/Business> ./bkupct.rb -s dude -d yo purge them all split Source path.......: dude Destination path..: yo Verbose is........: OFF Command line was..: -s dude -d yo purge them all split Arguments.........: purge them all split getopts list......: s:d:v The rookie mistake is that there was a mismatch between the values in the options I passed into the class to initialize() and the value I am using to index the elements of the returned params hash in initialize(). The params hash is indexed using just the letters, whereas options still has the colons which getopts needs. The closure I was expecting to create with the params hash was working, it was just indexing wrongly. So a simple sub! took care of this and now it works EXACTLY as I would like. Now, if someone can explain to me WHY I had to call the define_method() method using send() instead of calling it outright, I'd really like to know why that is. Why can't I do this?: class Options attr_reader :args, :cmdline, :options_list def initialize( options ) @cmdline = ARGV.join( ' ' ) @options_list = options.values.join params = ARGV.getopts( @options_list ) options.each do |key,value| value.sub!( /:/, '' ) ## Why can't I just do this?! self.define_method( key ) { params[value] } end @args = Array.new( ARGV ) end end Thanks all! -pj -- Posted via http://www.ruby-forum.com/.