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
2Jan/111

Fractal Rendering

I had some vacation time recently and wanted to explore HTML5/Canvas and fractals, so I wrote a basic JavaScript-based Mandelbrot renderer. The code is available in my GitHub repository, and the demo page is here. It takes about 10-15 seconds to render a single scene. This would be a good application for parallelization, but there's generally only a single thread available to JavaScript within the browser. Perhaps there's an opportunity to add support for HTML5 worker threads here.