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!
CodePudding user response:
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
CodePudding user response:
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)
CodePudding user response:
In your program: in swap function the return you have given is return a,b = b,a
remove a,b
and 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