Skip to content

Instantly share code, notes, and snippets.

@jensendarren
Created January 8, 2015 12:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jensendarren/0311418311ae18149081 to your computer and use it in GitHub Desktop.
Save jensendarren/0311418311ae18149081 to your computer and use it in GitHub Desktop.
An example of using OptionParser in Ruby
# Restrict arguments to a specified class.
require 'optparse'
class HelloParser
def self.parse(args)
options = {}
opts = OptionParser.new do |opts|
opts.banner = "Usage: name"
opts.on('-n', '--name NAME', 'The name of the person to say hello to') do |name|
options[:name] = name
end
opts.on('-t', '--times TIMES', OptionParser::OctalInteger, 'The number of times to say hello') do |times|
options[:times] = times
end
end
begin
opts.parse(args)
rescue Exception => e
puts "Exception encountered: #{e}"
exit 1
end
options
end
end
options = HelloParser.parse(ARGV)
repeat = options[:times].nil? ? 1 : options[:times]
if options[:name]
repeat.times do
puts "Hello, #{options[:name]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment