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:
Rather than:
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.
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. |