Command-line Arguments in Ruby on rails

By: Brian Marick Emailed: 1784 times Printed: 2623 times    

Command-line arguments are available as strings in the array named ARGV. For example, consider this command line:

prompt> ruby differences.rb old-inventory.txt new-inventory.txt

Within differences.rb, ARGV[0] will name (that is, provide a way to refer to) the string "old-inventory.txt", and ARGV[1] will name "new-inventory.txt".

Instead of “hard-coding” the two files’ names into the script, we can require the user to give them on the command line. The code to do that would look like this:

old_inventory = File.open(ARGV[0]).readlines

new_inventory = File.open(ARGV[1]).readlines

If you give no arguments to a script, ARGV still names an array, but it’s empty. You can see that using irb. irb is just a Ruby script, and you start it without any arguments, so. . .

prompt> irb

irb(main):001:0> ARGV

=> []

irb(main):002:0>

Since there’s nothing in the array, every array index is out of bounds and will return nil:1

irb(main):003:0> ARGV[0]

=> nil

irb(main):004:0> ARGV[1]

=> nil

Because ARGV[0] is nil, the script has a problem when it hits this line: 

old_inventory = File.open(ARGV[0]).readlines

Ruby’s unless construct begins with unless and ends with end. The body body is the text between the two. Unless the expression following the unless is true, the body is executed. Otherwise, it’s skipped. In this case, the body is executed unless the number of elements in the array is equal to 2 (meaning that both arguments were given).2

The body of an unless is just like any other Ruby code; it executes one line at a time. In this case, it prints a message. Then it uses the exit message to stop the script; otherwise, Ruby would continue to try (and fail) to open a file. You don’t have to indent the body, but it makes the code easier to read. I usually indent two spaces.

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)

Comment on this tutorial