def foo(x)
return x, x+1
end
a, b = foo (10)
#=> [10, 11]
a
and b
automatically gets assigned to the values returned by the function. Besides this, Ruby has the ability to define how variables are being assigned as well. For example:a, b, c = [1, 2, 3, 4]
p a, b, c
1
2
3
a, b, *c = [1, 2, 3, 4]
p a, b, c
1
2
[3,4]
Notice the asterisk(*) before the
c
variable, where the remaining values of 3
and 4
got assigned into the variable c
as an array. Neat!
3 comments:
Sweet!
Thanks for positing that! I was trying to get it to work, but hadn't realised you need an explicit "return" for multiple values.
Thanks a lot!!
Post a Comment