How to return multiple values from a method

The following is easy stuff but we tend to forget about it… probably because most of us are not used to this kind of behavior from a programming language.

Ruby gives the illusion that you can return more than one element from a method.

This is how you do it :

It’s important to note that even though it doesn’t look like it, only ONE thing is returned from this method. This thing is, you bet, an array.

In fact,

is equivalent to :

Ruby arranges things both on the sending and receiving end to make it look like you are returning more than one element.

  • Chris

    This is also how MATLAB handles multiple outputs from functions. Pretty swish.

  • Alex

    That’s pretty cool. It’s a bit of a shame that you can’t do:
    do_whatever if a_method_to_insult_innocent_people
    I guess you could do a_method_to_insult_innocent_people.first instead, although that seems a little ugly.

  • Frank


    Good observation. It’s true that you have to be careful with statements like “do_whatever if a_method_to_insult_innocent_people” (since it will always return true).

    I don’t dislike your solution (a_method_to_insult_innocent_people.first) but I think I would prefer : a_method_to_insult_innocent_people[0]. It may feel “less ruby” but it has the advantage of being clear about what the return value really is (an array). On the other hand, if you use “.first”, some could think that your method returned a custom object that contains a method named “first”. Anyway, just a personal taste thing :)

    Thanks for your comment

  • RSL

    There’s another reason that Alex’s solution might be less than idea. If you’re returning multiple values but only using one then you’re probably better off with a different method.

  • Alex

    You are right RSL, although it was a convuluted example. A real world example of usage might be:
    @insult_result = a_method_to_insult_innocent_people

    In which case both values are used.

    To be honest though, returning a hash would probably be nicer for everyone involved :).


  • Alex

    Sorry contrived, not convuluted (spelt wrong anyway).


  • Pingback: Learning Ruby & Rails - July edition |

  • Alexwebmaster

    Hello webmaster
    I would like to share with you a link to your site
    write me here