Reputation: 475
I'm starting to learn Ruby. I read that arguments where passed by reference to a method, however I don't understand the difference between these two methods.
def print(text)
puts text
end
and
def print(*text)
puts text
end
Using a *
means that we are passing a pointer like in C?
Upvotes: 2
Views: 179
Reputation: 2261
First you have two nice methods started there. But I would say try to avoid using puts inside them. You don't need it anyway. A method will always yield the last statement evaluated. something = text would get the job done. And I don't need to answer now about the differences. Your first two replies are very good there. But you may want to try something like this j = *[] #=> nil in 1.8 but [] in 1.9 It's been the new kid on the block for a time now. Guess what it does?
Upvotes: 0
Reputation: 66837
There are no pointers in Ruby, *
in this context is generally referred to as the "splat" operator:
In this case the method can take an arbitrary number of arguments, which will be available in the array text
.
Upvotes: 2
Reputation: 9618
The *text is what's called the splat operator in Ruby. It basically means if you pass multiple arguments to the second print they will get slurped into the single text variable.
See The Splat Operator in Ruby
Upvotes: 5
Reputation: 79961
The *
before a parameter name in a Ruby parameter list is used for variable length arguments, so they are similar to the ...
in C/C++ for varargs.
def vlaFunc(*args)
puts args
end
vlaFunc(1,2,3)
# output is [1,2,3]
Upvotes: 4