Created
June 27, 2013 21:56
-
-
Save caseyscarborough/5880746 to your computer and use it in GitHub Desktop.
A small script that demonstrates option parsing in Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'optparse' | |
options = {} | |
# Create new options parser | |
OptionParser.new do |opt| | |
# Set the help message banner | |
opt.banner = "Usage: #{opt.program_name}.rb [options]" | |
# Specify options and set the respective values in the options hash | |
opt.on('-q','--quiet','Quiet mode') { |o| options[:quiet] = o } | |
opt.on('-i','--interactive','Interactive mode') { |o| options[:interactive] = o } | |
opt.on('-f FILENAME','--file FILENAME','Specifies filename') { |o| options[:filename] = o } | |
# Set the options that show the help menu (created by OptionParser) | |
opt.on('-h','--help','View the help menu') { puts opt; exit } | |
# Show help menu if no arguments specified | |
if ARGV.length == 0 then puts opt; exit end | |
# Parse arguments and abort if exception | |
begin | |
opt.parse! | |
rescue Exception => e | |
abort e.message | |
end | |
end | |
puts options | |
if options[:quiet] then puts "You're running in quiet mode!" end | |
if options[:interactive] then puts "Interactive mode activated!" end | |
if options[:filename] then puts "You specified a filename: #{options[:filename]}" end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment