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 :
def a_method_to_insult_innocent_people error = compute_error if error == :stupid return false, "You made a stupid error" elsif error == :ridiculous return false, "You made a ridiculous error" elsif error == :worst_of_all_time return false, "You made the most idiot error in history. Way to go..." else return true, "You made no error, you are still an idiot" end end success, msg = a_method_to_insult_innocent_people do_something_with_success(success) destroy_hateful_words!(msg)
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.
return false, "you made a stupid error"
is equivalent to :
return [false, "you made a stupid error"]
Ruby arranges things both on the sending and receiving end to make it look like you are returning more than one element.
8 thoughts on “How to return multiple values from a method”
This is also how MATLAB handles multiple outputs from functions. Pretty swish.
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.
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. 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
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.
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 :).
Sorry contrived, not convuluted (spelt wrong anyway).
I would like to share with you a link to your site
write me here [email protected]