2009/11/3 Jillian Kozyra <
jillyh0@...>:
> I am trying to write a ruby script which accepts a flag. That is, I
> would like to execute the script by doing:
> ./assignment2.rb --verbose OR
> ./assignment2.rb
>
> How would I got about making the script accept a flag?
You would use one of the option parsing libraries around. The
standard lib comes with OptionParser and GetoptLong. There are also
other libraries and gems around that do option processing (and
sometimes more). With OptionParser you could do
require 'optparse'
$verbose = false
OptionParser.new do |opts|
# simple
opts.on '-v', '--verbose', 'Print verbose messages' do
$verbose = true
end
# alternative: with negation
opts.on '-v', '--[no-]verbose', 'Print verbose messages' do |flag|
$verbose = flag
end
end.parse! ARGV
puts "verbose is on" if $verbose
Note that OptionParser also gives you some default options, for
example "-h" and "--help".
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/