Alle venerd=C3=AC 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
=3D=3D=3D=3D=3D=3D
How do I program it so it runs in command line?
so:
=3D=3D=3D=3D
ruby coolest.rb "cool" "est"
=3D=3D=3D=3D
it'll output:
coolest
=3D=3D=3D
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=20
OptionParser at all. Command line arguments and options are stored in the=20
ARGV array. For example, if you do:
ruby my_program.rb -a --b-with-long-name=3D3 arg1 arg2
ARGV will be:
["-a", "--b-with-long-name=3D3", "arg1", "arg2"]
In your example case, you can do (note that Coolest Program is not a valid=
=20
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 tw=
o=20
situations, depending on whether you use OptionParser#parse! or=20
OptionParser#parse. Both methods return the command line arguments, but the=
=20
first also changes ARGV removing all the options, so that it will contain=20
only the arguments.
=46or example, take the following script:
#!/usr/bin/env ruby
require 'optparse'
opts=3D{}
o =3D OptionParser.new do |o|
o.on("-v", "--verbose", "turn on the verbose flag"){opts[:verbose]=3Dtrue}
end
args =3D o.parse(ARGV)
puts "opts=3D #{opts.inspect}"
puts "ARGV=3D #{ARGV.inspect}"
puts "args=3D #{args.inspect}"
called with the command:
ruby program.rb -v 1 2 3
outputs:
opts=3D {:verbose=3D>true}
ARGV=3D ["-v", "1", "2", "3"]
args=3D ["1", "2", "3"]
If I replace the line o.parse(ARGV) with o.parse!(ARGV), I get
opts=3D {:verbose=3D>true}
ARGV=3D ["1", "2", "3"]
args=3D ["1", "2", "3"]
I hope this helps
Stefano