skip navigation

Here you will find ideas and code straight from the Software Development Team at SportsEngine. Our focus is on building great software products for the world of youth and amateur sports. We are fortunate to be able to combine our love of sports with our passion for writing code.

The SportsEngine application originated in 2006 as a single Ruby on Rails 1.2 application. Today the SportsEngine Platform is composed of more than 20 applications built on Rails and Node.js, forming a service oriented architecture that is poised to scale for the future.

About Us
Home

Shadowing Gotchas

11/07/2013, 9:00am CST
By Travis Dahlke

Little known facts about Ruby variable scoping

Recently, while working on one of those "WHY ISN'T THIS WORKING?!" bugs, I stumbled on what I believe is a little understood fact about Ruby variable scoping.

The code went something like this:

def foo; "foo"; end

foo = "bar" if foo.nil?
foo # => nil

How is this possible you ask? It turns out that in Ruby, local variables are determined to be in scope at parse time, not at runtime.

defined? foo # => nil
foo = "foo" if false
defined? foo # => "local-variable"

Without an explicit receiver or arguments, Ruby will always attempt to dereference the local variable if it is in scope.

foo # => nil
self.foo # => "foo"
foo() # => "foo"

To avoid this problem in practice, you should avoid shadowing method names with local variables in all but the simplest of cases. We actually had this guideline in our styleguide.

When writing or reviewing code, be on the lookout for shadows. You never know when they'll sneak up on you.

Tag(s): Home  Ruby