Returning more than one value


#1

Hi group.

I’ve tested the following:

irb(main):001:0> def foo
irb(main):002:1> 1,2
irb(main):003:1> end
SyntaxError: compile error
(irb):2: parse error, unexpected ‘,’, expecting kEND
1,2
^
from (irb):3
from :0
irb(main):004:0> def foo
irb(main):005:1> return 1,2
irb(main):006:1> end
=> nil
irb(main):007:0> a,b = foo
=> [1, 2]
irb(main):008:0> a
=> 1
irb(main):009:0> b
=> 2
irb(main):010:0>

So, the bottom line is “1,2” simply fails, but “return 1,2” succeeds.
However, as you know,

def bar
1
end

does return 1.

Why does 1,2 fail? Is there any reason?

Thank for your time.

Sincerely,
Minkoo S.


#2

1, 2 is not a valid expression using ruby syntax. Use something like
the following:

def my_action
[1, 2]
end

first, last = my_action

You return multiple values simply by returning an array which can then
be automatically split across a series of variables using Ruby’s
parallel assignment.