Forum: Ruby returning more than one value

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
47b36de21d7ecbc824c81d24802a6290?d=identicon&s=25 Minkoo Seo (pool007)
on 2006-03-01 08: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
  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 Seo
Be223e60c56535a0e465b84243aeb0d1?d=identicon&s=25 Timothy Goddard (Guest)
on 2006-03-01 12: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]
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.
This topic is locked and can not be replied to.