← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 6 of 6

ARGV

ARGV is the list of extra words typed after your script's name when you run it, like the toppings you call out when ordering. Your program can read them and act on them.

In this page:

  1. ARGV
Syntax
ruby
# ruby script.rb arg1 arg2
first = ARGV[0]
ARGV.each { |arg| puts arg }

ARGV

ARGV is a global array holding the command-line arguments passed to a Ruby script when it's run, excluding the script name itself.

ARGV[0] is the first argument, ARGV.length gives the count, and so on -- it behaves just like a normal array. This is the standard way a Ruby script reads input passed to it from the command line.

Note: ARGV always contains strings, even if an argument looks numeric -- convert with .to_i or .to_f if you need a number.

Example: ARGV

markup
# Simulating ARGV since this runs without real command-line arguments:
simulated_argv = ["report.txt", "--verbose"]

puts "Argument count: #{simulated_argv.length}"
puts "First argument: #{simulated_argv[0]}"
puts "In a real script, this data comes from the built-in ARGV array"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading ARGV[0] when no arguments were given, which is nil and then breaks.
  2. Expecting ARGV to include the script name, when it holds only the arguments.
  3. Forgetting that all ARGV values are strings, so ARGV[0] + 1 fails until you use .to_i.
Chapter Summary
  • File.read, File.write, and File.open with a block read and write files.
  • begin, rescue, ensure, and raise handle and signal errors.
  • Custom exceptions and ARGV support error types and command-line input.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.