Question

I have a question regarding the stars in this method:

def multiplies_array(*numbers)
  numbers.inject(1, :*)
end

What is the meaning of the star in the argument list (*numbers)? And what is the meaning of the star after the colon (1, :*)?

Was it helpful?

Solution

The first star is the splat operator. In this case it "collects" all parameters given to multiplies_array into a single Array.

Calling it like this with four parameters...

multiplies_array 1, 2, 3, 4

... gives you a single array with four elements in the method.

This is equivalent to:

def multiplies_array(numbers) # Without splat operator
end 

multiplies_array [1, 2, 3, 4]

The second star is a little confusing. Here the the multiplication operator is meant:

The : denotes a symbol. All Enumerable methods allow passing a symbol as a shortcut. It means: "Call the method with this name".

In other words the * method is applied to each item in the numbers array. Without the symbol shortcut that line would look like:

numbers.inject(1) { |result, number| result * number) }

I hope this sheds a little light on all that Ruby magic :)

OTHER TIPS

See the documentation for inject.

It "combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator."

So, the :* is specifying the multiplication operator in numbers.inject(1, :*) The :* specifies it as a symbol but you could do numbers.inject(1, '*') as well. Using a symbol is more idiomatic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top