Local Variable Scoping Rules in Ruby – Part One

DISCLAIMER: At the time of this post, I, John Gamboa, was not a Ruby or programming expert. A total noob and I wrote this more to familiarize myself with the rules than anything else. What flows through sticks to you.

A scope of a local variable determines if it is accessible or not. For instance, if you were to code this:

var1 = 1
loop do
  puts var1
  var1 = var1 + 1
  break
end
puts var1

Run the code and you’ll find that the last line “puts var1” results in 2 being displayed. Why? Because the variable var1 in the first line is accessible and there can be modified by the loop block.

Rule #1 – Outer scope variables are accessible by the inner scope.

But what about block of code? What does the last line produce?

array = [6, 5, 4]
for i in array do
  var1 = 5
end
puts var1

It produces 5. Even though var1 was initiated inside the do/end block, var1 is accessible outside it. For a variable to be inaccessible in a do/end block, the do/end block needs to immediately follow a method invocation. “for” in the code above is not a method invocation, in contrast to the following code:

loop do
  var1 = 1
  puts var1
  var1 = var1 + 1
  break
end
puts var1

Since “loop” is a method invocation, the do/end loop following it creates a new block which prevents var1 from being accessed by “puts” in the last line. It results in an error with “undefined local variable or method…” in it. That’s because var1 was initialized inside the loop block, or in the inner scope, and the “puts var1” is outside the block and can’t access var1.

Which means…

Inner scope variables are NOT accessible outside of the block

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s