Today I wanted to talk about passing multiple arguments to functions. This can be a very useful piece of functionality if used correctly. One good example of passing multiple values to a function would be is when an application needs to validate multiple email addresses before an email is sent out to all the people in the list. This way the method signature looks very clean and all the consumer of the method has to do is simply pass in an array of all of the emails that they want to validate.

Let’s take the following code as an example of what it would look like.

def return_valid_emails(*email_list)
new_list = Array.new
email_list.each do |email|
new_list << email unless not email.valid? end new_list end return_valid_emails("valid@email.com","invalid.com") [/sourcecode]

The method above has a strange looking variable that has a “*” symbol saying that the argument is a variable array of items. Once we are inside of that method the “email_list” variable is treated as a normal Array and we can write some logic to iterate through items in the Array and perform our validation logic.

This logic consists of creating a new Array of emails and we populate that new Array by iterating through the given list of emails and validating each one. After the iteration is complete we simply return the new Array to the caller. The output of the call should be the following:

[“valid@email.com”]

If anyone has any other questions in regards to what is happening in this method don’t hesitate to ask.