Forum: Ruby returning more than one value

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Minkoo S. (Guest)
on 2006-03-01 09:18
(Received via mailing list)
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
        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

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

def bar

does return 1.

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

Thank for your time.

Minkoo S.
Timothy G. (Guest)
on 2006-03-01 13:48
(Received via mailing list)
1, 2 is not a valid expression using ruby syntax. Use something like
the following:

def my_action
  [1, 2]

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.
This topic is locked and can not be replied to.