How to return multiple values from a method

by Frank

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..."
    return true, "You made no error, you are still an idiot"

success, msg = a_method_to_insult_innocent_people

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,

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.

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • Digg
  • Furl
  • Technorati
  • StumbleUpon