Tuesday, 4 February 2014

Ruby - Local Variables

A local variable is only accessible within the block of code in which it’s been made available. It being available only within the locality of the block of code is the critical thing. It’s easy to define local variables at a top level of your script and wonder why you can’t access them when you create a method or class for example. We’ll see examples of Methods and Classes below, but we’ll cover them in depth later on.

 We can prove that a local variable is only accessible at the local level by having two variables with the same identifier. Here’s a local variable defined at the main body / outer script level and one of the same name in a method.

Add this code to a new .rb file, then run it via a CMD window to see what happens.

# localVariable_001.rb
# Define the variable 'a' in the main body of the script
a = "First variable called a"

# Define another variable 'a' within a method
def method_001
    a = "Second variable called a"
    puts a

# Now call the outer and inner variables 'a' to see there's no clash
puts a

You’ll notice there’s no issue with two local variables using the same name (more correctly the name is an identifier). This shows us the ‘a’ in method_001 is only local to the method and the ‘a’ in the main body of the script is only local to the main body of the script. Try adding two variables with the same identifier in either the main body or in the method and see what happens. Seemingly no issue with defining two variables using the same reference, ah… except the second definition overrides the first definition, which makes sense right?

No matter if we have methods inside methods, inside classes, etc. it’s local scope all the way down for local variables! Local variables are safe as their scope is very much under control. If there’s an in house convention for naming say, two figures to be added or the output of an operation on something, we can use the same identifier and they’ll be no issue if the scope is local. It’s also more obvious when a script doesn't work because we can’t seem to get to a value, it’s scope is likely local.


Read More