rubycommand-lineoptparse

Simple explanation for this optparse example from Ruby


require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"

  opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
    options[:verbose] = v
  end
end.parse!

p options
p ARGV

I found this from the optparse documentation page here. Can someone please explain this example in layman terms? I read the documentation but, there are some parts I don't understand. Namely, the end.parse! and the difference between the methods parse and permute.


Solution

  • The end.parse! is not some magical kind of end if that's what you were thinking. It can be written like this:

    option_parser = OptionParser.new do |opts|
      opts.banner = "Usage: example.rb [options]"
    
      opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
        options[:verbose] = v
      end
    end
    
    option_parser.parse!