We've seen many variables already in rubymonk. However, we haven't much discussed how they vary in terms of visibilty. Visibility, or scope, is what differentiates kinds of variables (local, global, instance, and class) but also determines where a variable can be accessed from. Let's have a look.
While it may seem obvious at this point that
on_the_inside is not defined outside the method
scope_the_scope, it may not be entirely obvious why. Take a moment to consider how the Ruby interpreter is reading your code. If you remove the call to
scope_the_scope in the above example, Ruby still reads the
puts line... but it doesn't execute. Why?
Every time the Ruby interpreter encounters
def, it enters a new scope. This means simultaneously that it is capturing the code its about to read into a name (in this case, `scope_the_scope`) but also that it is creating a new context in which that code will be read. That context is the local scope, and it cuts both ways: variables defined inside the method cannot be changed or read outside the method -- variables defined outside the method cannot be changed or read inside the method.
Notice our use of Ruby's keyword
defined?. This is a special keyword in Ruby (like
if), not a method, because we would otherwise see
NameError for undefined variables. The same concept applies to instance variables, with an extended example:
As you can see,
defined? doesn't just report whether the variable is defined but also how it is scoped.
Scope will become an important topic when you start metaprogramming. When you read "Metaprogramming Ruby" and "Metaprogramming Ruby: Ascent" scope will come up frequently. The yin to scope's yang is binding, which is the Ruby terminology for the context we previously mentioned when discussing method definitions.