Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.