Alle venerdì 16 novembre 2007, Feng Tien ha scritto:
I'm trying to write an command line program.
For instance
if I have a class like this with 1 method
class Coolest Program
coolest_method (a,b)
puts a + b
end
end
How do I program it so it runs in command line?
so:
ruby coolest.rb "cool" "est"
it'll output:
coolest
===
aka insert the 2 arguments into the Coolest Program object? Can't seem
to figure this out, been searching the last hour. I get how to use the
OptionParser library to take options, but not arguments.
If you don't need to pass options but only arguments, you don't need
OptionParser at all. Command line arguments and options are stored in the
ARGV array. For example, if you do:
ruby my_program.rb -a --b-with-long-name=3 arg1 arg2
ARGV will be:
["-a", "--b-with-long-name=3", "arg1", "arg2"]
In your example case, you can do (note that Coolest Program is not a valid
name for a class):
class CoolestProgram
coolest_method (a,b)
puts a + b
end
end
CoolestProgram.coolest_method(ARGV[0], ARGV[1])
If you need to use OptionParser because you also need options, there are two
situations, depending on whether you use OptionParser#parse! or
OptionParser#parse. Both methods return the command line arguments, but the
first also changes ARGV removing all the options, so that it will contain
only the arguments.
For example, take the following script:
#!/usr/bin/env ruby
require 'optparse'
opts={}
o = OptionParser.new do |o|
o.on("-v", "--verbose", "turn on the verbose flag"){opts[:verbose]=true}
end
args = o.parse(ARGV)
puts "opts= #{opts.inspect}"
puts "ARGV= #{ARGV.inspect}"
puts "args= #{args.inspect}"
called with the command:
ruby program.rb -v 1 2 3
outputs:
opts= {:verbose=>true}
ARGV= ["-v", "1", "2", "3"]
args= ["1", "2", "3"]
If I replace the line o.parse(ARGV) with o.parse!(ARGV), I get
opts= {:verbose=>true}
ARGV= ["1", "2", "3"]
args= ["1", "2", "3"]
I hope this helps
Stefano