Hi,
I am slowly learning Ruby and for now I am really confused with one
thing.
When I am trying to pass arguments from the cli, I can’t understand why:
user = ARGV.first
and
file1, file2 = ARGV
works, but
file1 = ARGV
NOT
Does that mean when using ARGV and making from arguments variables,
there have to be more than one for using the second way?
Thanks in advace…
ARGV is an array, you can pass more than one arguments using comamnd
line if you want to pass only one element thats not a problem.
ARGV[0] will have your first argument.
ARGV.each do|a|
puts “Argument: #{a}”
end
Thank you, however, this is somewhat indirect answer. I am still
confused why one solution works just with two variables. When I am using
just one, I have to use another way.
cli> ruby ex66.rb test1.txt text2.txt
script ex66.rb>
first, second = ARGV
input = File.open(first)
…
output = File.open(second, ‘w’)
…
works perfectly, the simplest
cli> ruby ex66.rb test1.txt
script ex66.rb>
input = ARGV
input = File.open(input)
…
does not. I have to explicitly say input = ARGV.first, which is exactly
what I have not to in the first case.
Thanks, this is much closer.
However, I still can’t figure why only:
first = ARGV
does not work
I would expect that
first, second = ARGV
and
first = ARGV
are the same way of defining variables taken from the cli.
Honza Hejzl wrote in post #1152806:
first, second = ARGV
there are several variable on left part of assignment, so ruby
interprete this multiple assignement
first, second = *ARGV
which is equivalent to
first, second = ARGV[0],ARGV[1]
which is equivalent to
first = ARGV[0]
second =ARGV[1]
Wow, this could be a sort of magic…
first = ARGV[0] > works
first, = ARGV > works too!
first = ARGV.first > works!
first = ARGV > does not work
first, second = ARGV > works
first, second = ARGV[0], ARGV[1] > works