Omitting "return" from last line of a method def

I find myself in position of an old copy of SAMS TY Ruby in 21 Days; written in regard to Ruby version 1.7

I have version 2.7.2p137 installed and I am getting by OK (in the first few chapters anyway). The book claims that a method that doesn’t contain a line with “return” in it will go ahead and return the last expression it evaluates, so that

def sumdiff(n1, n2)
	n1+n2, n1-n2
end

will return (keep up with me) 18, 2 if given the arguments 10, 8.

But when I tried running that I got
syntax error, unexpected ‘,’, expecting `end’
n1+n2, n1-n2

And then it worked fine once I reran it with “return” where it should be.

Was this functional "return"lessness a feature in Ruby 1.7 that was later removed? Or am I still doing something wrong?

When you use return, you pass 2 arguments and you get an array. But if you omit return, you end up with something that makes no sense to Ruby.

If you type 1, 2 in bare Ruby, you get syntax error, because 1, 2 means nothing. You instead meant [1, 2].

Similarly, you need to return this:

[n1+n2, n1-n2]

In case of return, it accepts *args (multiple arguments), and returns the *args as an array for you. You can omit return, but you need to surround values in arrays if you are planning to return multiple values.

Thank you Sourav!! Indeed the SAMS book got it wrong : /

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs