Scoping Out Method Scopes

I have finally returned to Ruby and none too soon! Today, lets look at scopes in Ruby.

The scope of a program means that the variables we create do not exist everywhere in a program. This helps in preventing the programmer from overwriting a variable created by someone else (or, let’s be honest, themselves) in other parts of a program. I mean, it could still happen, but it reduces the risk.

Methods have their own scope. A variable created outside a method is unavailable to the method. This means if we set a variable outside of a method, and then create a method with variables inside that method, the variables outside the method are not accessible inside the method and vice versa. Let’s look at an example:

Now, in the above I have defined a variable outside of the method, my_name, and set it equal to Nick. When I run the Ruby file I get the immediate response below the defined method, #greeting, that puts the my_name variable to the screen. It also returns nil. Below that I call the #greeting method and pass in the argument “Sophie” which runs and spits out an error.

See here:

So, we see that outside the method that my_name variable is accessible. Inside the method, however, my_name is inaccessible. Let’s try something a little different. What if I have this?

What will happen? If you run the file, my_name variable will be puts to the screen and then we get an error. See here:

At this point the program stops, thus #greeting method is never called. Why? Because inside_voice is a method scope variable and inaccessible outside of it.