Skip to content

Method Definitions: Implicit vs. Explicit Returns

Jenny Nguyen edited this page Dec 2, 2015 · 1 revision

Ruby functions have an implicit return, meaning they return the last statement evaluated.

def string_message(str = '')  # str is an optional default argument
  if str.empty?
    "It's an empty string!"
  else
    "The string is nonempty."
  end
end

Ruby also has an explicit return option; the following function is equivalent to the one above:

def string_message(str = '')
  return "It's an empty string!" if str.empty?
  return "The string is nonempty."
end

The second return here is actually unnecessary. Because it is the last expression in the function, the string "The string is nonempty." will be returned regardless of the return keyword, but using return in both places has a pleasing symmetry to it.

Clone this wiki locally