ruby script with flag

J

Jillian Kozyra

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
 
R

Robert Klemme

2009/11/3 Jillian Kozyra said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,816
Latest member
nipsseyhussle

Latest Threads

Top