Forum: Ruby Error in method call - need help to understand

C23bb4dc03aee6e2c5df9d07ef82cf64?d=identicon&s=25 Pritam Dey (pritamdey)
on 2013-03-19 02:33
I was trying to call a method as below:

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

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

parser (array_1,array_2)
puts $array

D:/Rubyscript/My ruby learning days/Scripts/test.rb:13: syntax error, u
nexpected ',', expecting ')'
parser (array_1,array_2) # taking multiple arguments generates error

No I fixed the code by removing the space in the method call of parser
as below:

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

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

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


But in the first method why such `space` causes the errors to be thrown
B31e7abd14f1ceb4c4957da08933c630?d=identicon&s=25 Josh Cheek (josh-cheek)
on 2013-03-19 02:51
(Received via mailing list)
On Mon, Mar 18, 2013 at 8:33 PM, Pritam Dey <>

> end
>                 ^
>     $array << item
> salmon
> Posted via

In Ruby, you do not have to use parens around a method. So `method(arg)`
 can be written as `method arg`. Lets say arg was some expression, you
might want to put parens around it to make it clearer. `method (true &&
false)` which corresponds to `method((true && false))` So when you say
`parser (array_1, array_2)`, that becomes `parser((array_1,array_2))`
`(array_1, array2)` is not a valid expression in Ruby.

That is what is meant here (
when he says "Instead of treating array_1 and array_2 as args, it's
treating it as a parenthesized expression"

F141ba99f29e55f02207f5488fe5ce95?d=identicon&s=25 Dave Aronson (Guest)
on 2013-03-19 17:29
(Received via mailing list)
To expand a bit on Josh Cheek's reply:

In general, get in the habit of not leaving a space before the opening
paren of a function call that uses parens.  That's what trips up the
parser and makes it think you're passing one malformed expression, not
multiple arguments.  This used to trip me up in my early days of Ruby,
because my standard coding style DID include a space there....

Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.