yukimoda yukimoda - 1 year ago 59
Ruby Question

Require a file to be called from the command line

So I know how to use optparser to use the command line to call a specific method in my program. But, is there a way to use optparse where the user is required to specify a file in order to have the command work? Like for example when using this code:

read = File.readlines(file)
puts read

The user would be required to specify a specific file the program needs to read.

test.rb -b test.txt

Is there a way to do this or am I still too new to ruby to fully understand how it works?

Answer Source

I don't know about optparse, but you can do something like this perhaps:

file = ARGV[0]
read = File.readlines(file)
puts read

then run the file in command line, passing the file name as an argument. Where ARGV[0] corresponds with the first argument passed:

$ ruby test2.rb test2.rb
#file = ARGV[0]
#read = File.readlines(file)
#puts read
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download