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..."
  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.

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
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon