Ruby’s splat operator

The splat operator can be used to create methods that accept a variable number of arguments. Here is how to create a method that adds a variable number of numbers passed as arguments.

def add(*nums)
  nums.inject(&:+)
end

>> add(1, 2)
=> 3
>> add(1, 2, 3, 4)
=> 10

The arguments collected by the splat operator will be accessible as an array in the method body.

def show_args(*args)
  args
end

>> show_args(1, 2, 3)
=> [1, 2, 3]
>> show_args("cool", "io")
=> ["cool", "io"]

The splat operator can also be combined with Ruby’s standard arguments to create a method that requires certain arguments, but is flexible about other arguments.

def combo(x, y, *args)
  puts "x: #{x}"
  puts "y: #{y}"
  puts "args: #{args}"
end

>> combo(2, 3, 7, 8, 9)
x: 2
y: 3
args: [7, 8, 9]
>> combo(1, 2)
x: 1
y: 2
args: []
>> combo("bob")
raises an ArgumentError because two arguments are required an only one was provided.

The splat operator can also be used to decompose an array as separate arguments for a method. The following example shows how the splat operator makes the [“Jess”, “Spaceman”, “M.D.”] suitable for a method that requires three arguments.

def full_name(first_name, last_name, title)
  "#{first_name} #{last_name}, #{title}"
end

person = ["Jess", "Spaceman", "M.D."]
>> full_name(*person)
=> "Jess Spaceman, M.D."
>> full_name(person)
raises an ArgumentError
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s