13aal 13aal - 2 years ago 74
Ruby Question

Correct way to parse arguments using ARGV

I've written a program that uses

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"
puts "Help page"

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

Answer Source

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"

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download