Ruby OptParse example

An example of command line argument handling including deletion of argument options

# wc.rb
 
require 'optparse'
 
ProgramOptions = Struct.new(:onlyChars, :onlyWords, :onlyLines)
 
options = ProgramOptions.new(false, false, false)
 
opts = OptionParser.new
 
p options
 
opts.on("-c","--char") { options.onlyChars = true; ARGV.delete("-c"); ARGV.delete("--char") }
opts.on("-w","--word") { options.onlyWords = true; ARGV.delete("-w"); ARGV.delete("--word") }
opts.on("-l","--line") { options.onlyLines = true; ARGV.delete("-l"); ARGV.delete("--line") }
 
opts.parse(ARGV)
 
p options
p ARGV

rubyoptparse.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0