Search code examples
rubycommand-lineoptparse

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:

test.rb    
#!/usr/bin/ruby
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?


Solution

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

    #test.rb    
    #!/usr/bin/ruby
    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
    ##test.rb    
    ##!/usr/bin/ruby
    #file = ARGV[0]
    #read = File.readlines(file)
    #puts read