Programming
Simple Ruby Tip – Return Multiple Values
September 16, 2017
0

Return Multiple Values

As many of you already know, everything in Ruby is an object so, when you create a method, it actually returns an object.
What I want to show here is how to return multiple values (multiple objects) out of a Ruby function.

Unfortunately Ruby does not support the returning of multiple objects, however what it supports is parallel assignment so, if you have two or more objects on the right side of an assignment, Ruby is so nice that it packs them in an array:

  def foo
    a = 1
    b = 2
    return a,b
  end
  puts foo.inspect

will have, as a result

[1,2]

This result can be also reached in this way

  def foo
    a = 1
    b = 2
    [a,b]
  end

Now, if we build an assignment in the follwing way:

   a, b = foo

each variable on the left side, will be bound to an element of the array on the right side.

   a = foo[0]
   b = foo[1]

This obviously works also with more than two objects. After writing something like this:

   a, b, c = foobar

what we will have will be something like the following snippet:

   a = foobar[0]
   b = foobar[1]
   c = foobar[2]

Another nice thing to notice is that if the right side of an assignment is not an array, Ruby will do a conversion using to_ary method, which is used for implicit conversions. This means that the original object will not be converted to an array, like using to_a, but it will be treated as an array:

  class Something < Array
  end

  Something[].to_a.class # this will return Array

  Something[].to_ary.class # this will return Something

Enjoy

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close