13aal 13aal - 6 months ago 12
Ruby Question

Correct way to parse arguments using ARGV

I've written a program that uses

ARGV
as the arguments, due to me not being able to install external gems.

What I'm doing so far is this:

if ARGV[0] == '-h'
puts "Help page"
elsif ARGV[0] == '--example'
puts "Examples page"
elsif ARGV[0] == '-t'
puts "Gathering intel"
elsif ARGV[0] == '--version'
puts "Version mode"
elsif ARGV[0] == '--dev-mode'
puts "developer mode"
else
puts "Help page"
end


This doesn't seem idiomatic to me. So my question is, is there a correct way to parse
ARGV
arguments from a Ruby script? I've done some research and seen people using
ARGV.shift
and such, is this "preferred" in the Ruby world?

Answer

OptionParser might be the right choice for possibly complicated parameters list.

Regarding your code, I would rewrite it that way:

puts case ARGV[0]
     when '-h' then "Help page"
     when '--example' then "Examples page"
     ...
     end

Here is a DRY principle taken into account: one puts, since each branch does puts, ARGV[0] mentioned only once etc.

Array#shift makes sense while you are looping through arguments array unless it is empty, since it removes the element from the array. In pseudocode that might look like:

 while opt = ARGV.shift do
   puts case opt
        when '-h' then 'Help requested'
        when '-f'
          file = ARGV.shift # requires subsequent arg
          # possible check for value is valid
          do_smth_with_file file
        ...
        end
 end
Comments