Within the Scope of This Article
With one exception that I discuss further below, in Ruby any local variable declared outside of a method has no effect within a method. And vice versa.
Let’s take a look at this example.
I created the name variable in line 1, before and outside of the method that I then defined in lines 2 through 4, wherein the name variable has not been assigned any value. Therefore, when I tried calling the method in line 5, I got an “undefined local variable… ‘name’” error.
But what happens when I add one more line to the method, and use it to create another name variable?
Once again, the name variable from line 1 is invisible to the method. But because I created another name variable within the method, there was no error. Instead, the method recognized and utilized its own name variable. And outside of the method, the value of the name variable remains “Omar”, the very same value that I assigned it in line 1, as you can see in the following screenshot.
So we see that any local variable within a Ruby method is never recognized outside of that method. And any local variable from outside a method is never recognized inside that method, unless it gets passed in.
As in the first example above: a name variable was created in line 1, before and outside of the method that was then defined in lines 2 through 4; and no name variable was created within the method. But this time there was no error. That’s because in line 3 the method was designed to be called with an argument; and when the method was called in line 5, the name variable was passed in as the argument. Just to avid any confusion (or possibly create some), let’s look at another example.
Again, the name variable is created in line 1. But in line 2 the method is designed to accept an argument that appears as “numeral”. It still all works out the same, though. That’s because the name variable that was created in line 1 is being passed to the method in the calling of the method on line 5. The “numeral” argument in line 2 is simply there so that when the method gets called and reaches “numeral” in line 3, it will view that as a reference to whatever argument it’s been passed. So the argument in line 2 could just as easily be “expialadocious” as long as “expialadocious” is then used in line 3. Let’s see what happens if there’s a mismatch between the argument in line 2 and line 3.
When “numeral” is used in line 2 and then “name” is used in line 3, there’s an “undefined local variable… ‘name’” error, just as when “name” is used in line 2 and “numeral” is used in line 3. Hopefully, that provides some clarity, both about how a method is designed to accept an argument and about how that’s different than passing a variable to a method.