Reputation: 32721
join is used to convert an array to a string. In the following, *names
is joined, and is output. Does this mean arguments are array?
def introduction( age, gender, *names)
"Meet #{names.join(" ")}, who's #{age} and #{gender}"
end
puts introduction(28, "Male", "Sidu", "Ponnappa", "Chonira")
This outputs:
Meet Sidu Ponnappa Chonira, who's 28 and Male
Upvotes: 2
Views: 269
Reputation: 11343
Here is code that shows what the *args ends up being, with examples of optional argument, greedy argument and required argument.
def something(name = 'Joe', *args, last_name)
puts name, args, last_name
puts args.inspect
puts "Last name is #{last_name}"
end
something "one", 'Smith'
# >> one
# >> Smith
# >> []
# >> Last name is Smith
The * (splat) operator says to accept 0 or more arguments, and it does not need to be the last in the list. Now with named arguments, it would be surprising if it would, given that named arguments needs to be last, if I remember correctly.
The 0 or more arguments will be stored in an array.
You can use the code above to start making changes and explore this.
Upvotes: 2
Reputation: 58324
When you pass *names
to introduction
then you get a Ruby Array of names
. The asterisk (*
) means it's variable length. The join
member of the Array
class in Ruby converts each member of the array to String (if they are convertible) and concatenates them together using the parameter to join
as a delimiter.
Note that all of the arguments to a method together do not form an Array. That is, age
, gender
, *names
together are not passed in as an array but are simply separate arguments to the method.
Upvotes: 2