Skip to content

Instantly share code, notes, and snippets.

@FaisalAl-Tameemi
Last active July 26, 2016 00:38
Show Gist options
  • Save FaisalAl-Tameemi/4b522102a4a9ab70bd3b4be69fdc6a06 to your computer and use it in GitHub Desktop.
Save FaisalAl-Tameemi/4b522102a4a9ab70bd3b4be69fdc6a06 to your computer and use it in GitHub Desktop.

ARGV in Ruby

What's ARGV?

ARGV is a convention in programming which refers to the “argument vector,” in basic terms a variable that contains the arguments / parameters passed to a program through the command line.

Typically an array with contains each argument in a certain position within the array. This may work differently in languages other than Ruby.

Example of ARGV

Create a new file called argv_example.rb and type the following code into it:

# print the argument vector
puts ARGV

# create an empty hash
person = Hash.new

# add data from argument vector by using argv
person[:name] = ARGV[0]
person[:age] = ARGV[1].to_i
person[:status] = ARGV[2]

puts person

In your terminal

ruby argv_example.rb Faisal 23 fantastic

So let's look at what this is doing...

  1. We created a file that we can run from the terminal using ruby
  2. Inside of the file, we start with printing the argument vector to checkout it's contents
  3. We notice that's it's actually an array of strings
  4. Read each value to set it to a property inside the person hash (note that we changed the second argument inside of ARGV into a number, this is because we're getting an array of strings for we need age as an integer)
  5. Print the person Hash object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment