Ask Your Question
1

Is it possible for OptionParser to disregard unfamiliar options and handle them in a Ruby program at a later time?

asked 2021-08-05 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-30 17:00:00 +0000

lalupa gravatar image

Yes, it is possible for OptionParser to ignore any unknown options and handle them in a Ruby program at a later time. This can be done by specifying the ignore_invalid_options option when creating the OptionParser instance. This will cause the parser to ignore any options that it doesn't recognize and store them in the non_options array. These options can then be processed by the Ruby program using the non_options array. Here's an example:

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.on("-f", "--file FILE", "Specify file to use") do |file|
    options[:file] = file
  end

  # Ignore any unknown options
  opts.ignore_invalid_options = true
end.parse!

puts "File specified: #{options[:file]}"
puts "Unknown options: #{ARGV}"

# Handle unknown options here

In this example, the ignore_invalid_options option is set to true, indicating that the parser should ignore any unknown options. The non_options array can be accessed using the ARGV constant, which contains any arguments that were not parsed as options.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-05 11:00:00 +0000

Seen: 9 times

Last updated: Oct 30 '21