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.
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...
- We created a file that we can run from the terminal using ruby
- Inside of the file, we start with printing the argument vector to checkout it's contents
- We notice that's it's actually an array of strings
- 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)
- Print the person Hash object