Search code examples
rubyinjectsplat

Please explain this method


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, :*)?


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 :)