I have a basic question about the mearning of * in a function call which I haven't been able to understand from online docs:
def self.new(*args, &block)
What does *args mean in the function call above?
I have a basic question about the mearning of * in a function call which I haven't been able to understand from online docs:
def self.new(*args, &block)
What does *args mean in the function call above?
It means you can pass any number of arguments that will be stored in args
table inside of this method. Take a look: https://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/
consider a following method
def user(user_name)
puts user_name
end
so when you call
user("RPV")
Output:
RPV
=> nil
but what if you pass more then one argument like
user("RPV", "Marek")
it will give an error
wrong number of arguments (2 for 1)
To avoid this kind of error splat(*) operator is helpful
def user(*user_name)
puts user_name
end
and when you pass more than one argument it handles converts it in array
user("RPV", "Marek")
output:
RPV
Marek
nil
it makes user_name as an array
def user(user_name)
p user_name
end
user("RPV", "Marek")
output:
["RPV", "Marek"]
Hope you got the use of it.