Measure Twice, Byte Once Making Stuff

17Jul/110

Implicit vs Explicit Returns in Ruby

Ruby supports implicit returns, i.e., the value of the last expression in a block/statement is what will be returned.  One might assume that  implicit returns and explicit returns(e.g. "return 123") are functionally equivalent.  Although this is often the case, there is a gotcha scenario when using an explicit return within a block.  In the following Gist, an explicit return is used within a map block.  The result is that explicitReturn() will end up returning a single upper-case string("PANGOLIN"), rather than an array of upper-case strings.

# Simple demonstration of an 'implicit' return
def implicitReturn()
  "implicit return\n"
end

# Simple demonstration of an 'explicit' return. Using an explicit return,
# even within a block, will exit the function.
def explicitReturn()
  examples = ["pangolin", "cat", "macgyver"]

  largerExamples = examples.map { |item|
    # Explicit return will return the first item in uppercase, rather than
    # allowing us to map our array
    return item.upcase
  }

  #This line will not be executed
  largerExamples
end

print implicitReturn() # Output: implicit return
print explicitReturn() # Output: PANGOLIN

view raw returns.rb This Gist brought to you by GitHub.

On a semi-related note, Martin Hsu provided my Pangolin inspiration: http://www.martinhsu.com/pangolin-rider-p-50.html

Filed under: Coding, Gotchas, Ruby No Comments