Forum: Ruby ARGV logic (cli arguments into variables)

4719e9e0162789b66f578a7e7f530b26?d=identicon&s=25 Honza Hejzl (welblaud)
on 2014-07-18 13:37
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...
379bab738b06250a3a804744710de870?d=identicon&s=25 Pardeep Dhingra (pardeepdhingra)
on 2014-07-18 14:23
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
4719e9e0162789b66f578a7e7f530b26?d=identicon&s=25 Honza Hejzl (welblaud)
on 2014-07-18 14:41
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.
B078cb4f4fb473c7a54d1fc36d10c70e?d=identicon&s=25 Regis d'Aubarede (raubarede)
on 2014-07-18 15:13
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]
4719e9e0162789b66f578a7e7f530b26?d=identicon&s=25 Honza Hejzl (welblaud)
on 2014-07-18 18:47
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.
4719e9e0162789b66f578a7e7f530b26?d=identicon&s=25 Honza Hejzl (welblaud)
on 2014-07-18 20:00
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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.