What does args
mean, and what is different between it and ARGV
if there is a difference?
def puts_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
What does args
mean, and what is different between it and ARGV
if there is a difference?
def puts_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
In this case, *args and ARGV have nothing to do with each other. In your example:
def puts_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
*args is just the parameters passed to the method puts_two. The * is the 'splat' operator, which means any number of arguments can be passed to the method and they will be 'splatted' in to an array. So if you called it with:
puts_two('one', 'two', 'three')
args will be an array that looks like ['one', 'two', 'three'].
Notice that in the assignment of the variables arg1 and arg2 only the first 2 elements of the array will be used, so using my example above
arg1, arg2 = ['one', 'two', 'three']
arg1 => 'one'
arg2 => 'two'
ARGV is simply the arguments passed to the ruby script from the command line.
This is referred to as the "splat operator" in Ruby. See the following article for different uses:
In a method definition it basically just gathers all remaining arguments into a single array (note that since Ruby 2.0 there's also the possibility to gather keyword args with something like **kwargs
).
*
is called splat operator.In *args
here *
creating an array with all the arguments sent to the method puts_two
, and args
as a local variable holds the reference to the array. In more clear way - The splat operator is used to handle methods which have a variable parameter list(ie Arraying your arguments).
ARGV
contains the arguments passed to your script, one per element.
For example:
$ ruby argf.rb -v glark.txt
In argf.rb
file, you will get as below :
ARGF.argv #=> ["-v", "glark.txt"]
ARGV is a special variable in Ruby. It contains the arguments passed to the script on the command line. For example, if you write the following code in a file called test.rb:
ARGV.each do |a|
puts a
end
and call it like this
c:\> ruby test.rb one two
will display
one
two
In the code you posted, *args
simply indicates that the method accepts a variable number of arguments in an array called args
. It could have been called anything you want (following the Ruby naming rules, of course).
So in this case, args
is totally unrelated to ARGV
.