Saturday, May 24, 2008

Multiple return values and assignments in Ruby

One of the things that I really liked about Ruby which extends to those non old-school computing languages as well, is the capability to return multiple values. For example:
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:

Anonymous said...

Sweet!

Anonymous said...

Thanks for positing that! I was trying to get it to work, but hadn't realised you need an explicit "return" for multiple values.

Anonymous said...

Thanks a lot!!

Post a Comment