Step 22: Variable Scope


Check out the following code:

def test_method
    test_variable = 358
end


test_variable + 5

The above code raised an error! If we read the error, Ruby is telling us that the variable test_variable hasn’t been defined. But didn’t we define that variable inside of test_method? Ruby can’t see that variable from the main program in test_method because of a concept called variable scope. Whenever you define a variable inside of a method, it will only be available inside of that method. You cannot access that variable, called a local variable, from the main program or another method. We can even have variables with the same names in different locations that won’t interfere with one another.

important_var = "do not change me"




def do_some_stuff
    important_var = "we’re going to change this"
    important_var = important_var.capitalize
    puts(important_var)
end


puts(important_var)
do_some_stuff
puts(important_var)