Skip to content

Instantly share code, notes, and snippets.

@synsa
Forked from jensendarren/optparse_example.rb
Created July 24, 2018 19:04
Show Gist options
  • Save synsa/4ad8df63e4449751ad42d87ef5ea54bd to your computer and use it in GitHub Desktop.
Save synsa/4ad8df63e4449751ad42d87ef5ea54bd 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