An example of using OptionParser 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
# 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