2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

What is strong params?
I will let the Ruby Rogues answer that question.
@vgoff, you have mistaken named parameters (which are Ruby feature) and strong parameters (which are ActiveRecord feature).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.