Someone explain to me the logic behind ARGV[0]

K

Kaye Ng

For example there's a code
lines = File.readlines(ARGV[0])
Why do i need the [0]?

I have another program, testingargv.rb with this code
puts ARGV.join('-')
(no [0] parameter)
if i type in the command prompt, testingargv.rb test 123
the result is test-123

i don't understand the logic behind [0] in
lines = File.readlines(ARGV[0])

thanks guys!
 
S

Stefano Crocco

For example there's a code
lines = File.readlines(ARGV[0])
Why do i need the [0]?

I have another program, testingargv.rb with this code
puts ARGV.join('-')
(no [0] parameter)
if i type in the command prompt, testingargv.rb test 123
the result is test-123

i don't understand the logic behind [0] in
lines = File.readlines(ARGV[0])

thanks guys!

ARGV is an array. Calling ARGV[0] returns the first argument of the array,
that is the first argument passed on the command line to the ruby script.
Calling ARGV.join('-') returns a string obtained by concatenating the elements
of the array with a - between each two of them.

The line

lines = File.readlines(ARGV[0])

assumes that the first parameter passed to the script on the command line is
the name of the file, so ARGV[0] contains the name of the file and
File.readlines(ARGV[0]) returns an array of the lines contained in that file.

For more information, see ri Array#[] and ri Array#join

Stefano
 
M

Marc Heiler

"Why do i need the [0]?"

The [0] just accesses the first member of the array, like for any other
array.
 
A

Alec Ross

Stefano Crocco said:
On Saturday 18 December 2010 19:12:57 Kaye Ng wrote: ....
For example there's a code
lines = File.readlines(ARGV[0])
Why do i need the [0]?

I have another program, testingargv.rb with this code
puts ARGV.join('-')
(no [0] parameter)
if i type in the command prompt, testingargv.rb test 123
the result is test-123

i don't understand the logic behind [0] in
lines = File.readlines(ARGV[0])

thanks guys!

ARGV is an array. Calling ARGV[0] returns the first argument of the array,

....

This naming and usage stems back to the C programming language. There,
argv is the conventional name for any command line arguments to the
program, and it denotes an array of c-style strings. Elements of an
array in C are accessed by a (0-based) index. Hence argv[0] gets the
first argument value, argv[1] the second, and so on.

HTH,

Alec
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top