Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Why does this method return three values?

I have following Ruby programm:

def swap (a,b)
   return a,b = b,a
end

puts swap(5,3)

I expected the output.

3
5

But I get.

5
3
5

What's the reason?

Thanks!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Why does this method return three values?

It's because of the return statement, Ruby tries to interpret the right-hand side as an array and your code:

return a,b = b,a

gets evaluated as: (parentheses added for clarity)

return [a, (b=b), a]

i.e. a 3-element array [a, b, a] (assigning b to itself does nothing)

over 4 years ago · Santiago Trujillo Report

0

Remove the keyword return. It is actually doing: return a, (b), a. Where (b = b)

def swap(a,b)
  a, b = b, a
end

puts swap(5,3)

Output

=> 3, 5
over 4 years ago · Santiago Trujillo Report

0

In your program: in swap function the return you have given is return a,b = b,a remove a,band diretcly write return b,a. you will get your expected output. Reason: in return a,b = b,a is return first the value of a then executing b=b,a. Hope this might help you out

def swap (a,b)
   return b,a
end

puts swap(5,3)

Output

3
5
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!