Ellie
Ellie

Reputation: 95

How to pass multiple arguments into a Ruby method

Passing one argument at a time into the parser method works. More than one and it generates "syntax error, unexpected ',', expecting ')' (SyntaxError)"

$array = []
array_1 = %w(tuna salmon herring)
array_2 = %w(crow owl eagle dove)

def parser (*argument)
  argument.each do |item|
    $array << item
  end
end

parser (array_1, array_2) # taking multiple arguments generates error
$array.flatten!
puts $array

Upvotes: 3

Views: 5958

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185671

It's the space before the parens. Remove it. Instead of treating array_1 and array_2 as args, it's treating it as a parenthesized expression (with the whole expression being one arg) and complaining about the comma. Your code should look like

parser(array_1, array_2)

Incidentally, Ruby 1.8.7 seems to simply emit a warning about this before behaving correctly.

Upvotes: 5

Related Questions