returning more than one value

M

Minkoo Seo

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
 
T

Timothy Goddard

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top