Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 55 / 68

Reading Command-Line Arguments

In this lesson you will learn to read command-line arguments with ARGV so you can build command-line tools. This is for anyone searching for "Ruby command-line arguments how to use".

When you run Ruby from the command line, the ARGV array holds the arguments. The example assumes you run it as ruby script.rb Alice 14.

The sample code takes a name and an age from ARGV[0] and ARGV[1], using the || operator to supply defaults when no argument was passed. Notice that ARGV, in capitals, is a built-in Ruby variable.

A common stumbling block for beginners is writing it in lower case, as $argv. Ruby's built-in is the capitalised ARGV, and getting the spelling or the case wrong stops it working.

It is the essential mechanism for scripts and tools you run from a terminal. It also serves as the basis of simple automation scripts that branch on the values supplied at run time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)