cameck cameck - 2 months ago 15
Ruby Question

Implicit Return in Ruby Returns Errors When Returning Two Values

Consider the following two code examples:

1



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

whaat, ya = yo

puts ya
puts whaat


2



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

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
2.+(2)
) 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
returns
behind the scenes as to me this shouldn't throw an error?

Answer

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.