Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does *args mean? [duplicate]

Tags:

ruby

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
like image 833
Ahmed Taker Avatar asked Aug 28 '26 01:08

Ahmed Taker


1 Answers

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.

like image 80
rainkinz Avatar answered Aug 30 '26 15:08

rainkinz