Computer Science Canada

Scoping, Conditionals and Loops

Author:  wtd [ Fri Oct 28, 2005 5:35 pm ]
Post subject:  Scoping, Conditionals and Loops

Coming from something like C, C++, Java, C# or one of the other similar languages, Ruby's scoping rules may seem a bit odd.

Things like loops and conditionals don't introduce a new scope.

We might seem something like this in C:

code:
void foo()
{
   int bar;

   if (some_condition)
   {
      bar = 27;
   }
   else
   {
      bar = 42;
   }

   printf("%d\n", bar);
}


Rather than:

code:
void foo()
{
   if (some_condition)
   {
      int bar = 27;
   }
   else
   {
      int bar = 42;
   }

   printf("%d\n", bar);
}


Because in the latter bit of code, "bar" is local to each block. Once that conditional goes out of scope, those declarations go away. Thus the "printf" call fails.

code:
def foo
   if some_condition
      bar = 27
   else
      bar = 42
   end

   puts bar
end


Since there is no new scope introduced, bar sticks around.

This could be seen as good or bad, but at least it is the way things are, and understanding it is important for any Ruby programmer.


: