Search code examples
rubyargvoptparse

run specific version of ruby script if command line argument is entered


I've read through tons of variations of my question, but I can't seem to find one that really matches up with what I'm trying to do.

I have a script that essentially has two versions: the "default" would run through a series of mandatory methods, and the second version would run through those same methods, then tack on a series of secondary methods. I would like the second version to be triggered from the command line (something like $ script.rb second_version), and the "default" option to be triggered by no argument input at all (since it's going to be used more frequently, so just $ script.rb).

I tried this with ARGV:

second_version = ARGV[0]

if second_version
   second_version_methods
else
  main_version
end

This technically works, but the problem is that the very first method that runs in the main_version script is a method that requires user input. What ends up happening is that the string "second_version" is automatically passed to that method as the value, which I don't want.

Essentially, is there a way to have a command line argument that will only specify a condition to run in a particular way, and then once that's done, it just drops the input? I've looked into optparse but its functionality seems a bit superfluous for this purpose.

Thank you!


Solution

  • ARGV isn't readonly, so you could consume the first input like this:

    if ARGV[0] == 'second_version'
      ARGV.shift # removes the first element 
      second_version_methods
    else
      main_version
    end
    

    If you want to keep ARGV intact (which is a better idea), you can do this:

    arguments = ARGV.dup
    
    if arguments[0] == 'second_thing'
      arguments.shift
    # ...