cameck cameck - 1 year ago 88
Ruby Question

Implicit Return in Ruby Returns Errors When Returning Two Values

Consider the following two code examples:


# Implicit Return
def yo
'swag', 'yolo'

whaat, ya = yo

puts ya
puts whaat


# Explicit Return
def yo
return 'swag', 'yolo'

whaat, ya = yo

puts ya
puts whaat

The first example returns this error:
syntax error, unexpected ',', expecting keyword_end
and the 2nd example works like a champ.

So, this got me curious as I know there a lot of shortcuts(idioms) in Ruby ( e.g.
2 + 2
is actually
) and if something is not working right always be clearer in your syntax and take the idioms out.

Thus, my question is how does Ruby handle
behind the scenes as to me this shouldn't throw an error?

Answer Source

Methods (and blocks, and class definitions, and module definitions) implicitly return the last expression evaluated. a, b is simply not a valid expression, it isn't even valid syntactically. return a, b is a valid expression: you are passing two arguments to the return keyword. Passing more than one argument, and leaving out the parenthesis is perfectly legal.

For a similar reason, foo(a, b) works, but foo (a, b) doesn't: the former is passing two arguments to foo, the latter is passing one argument (a, b) to foo, which is syntactically invalid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download