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:
Syntax
# 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
# 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"
Login to try C/C++/Java/PHP code in the editor
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
- Reading
ARGV[0]when no arguments were given, which isniland then breaks. - Expecting
ARGVto include the script name, when it holds only the arguments. - Forgetting that all
ARGVvalues are strings, soARGV[0] + 1fails until you use.to_i.
Chapter Summary
File.read,File.write, andFile.openwith a block read and write files.begin,rescue,ensure, andraisehandle and signal errors.- Custom exceptions and
ARGVsupport error types and command-line input.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: