Ruby script with flag

Hi,

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?

Thanks,
Jillian

Jillian K. wrote:

Hi,

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?

Thanks,
Jillian

Every command-line argument that you pass into a Ruby script is
available via the ARGV aray. Therefore, if you call a script with
./assignment2.rb --verbose
then ARGV[0] is “–verbose”. Because command-line-option-handling (what
a word!) can be a bit cumbersome, you could use a library like
OptionParser (in the stdlib as “optparse”).

Marvin

Jillian K. wrote:

Hi,

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?

Thanks,
Jillian

Command line options are stored in the ARGV array.

./assignment2.rb --verbose
ARGV[0] # => “–verbose”

If no command line options are supplied, ARGV will be empty.
Also look at optparse in the standard library for handling more
complex command line options.

Rob

2009/11/3 Jillian K. [email protected]:

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