Tuesday, 4 February 2014

I’m guessing you've already deduced what the scope of a Global variable is? Unlike local
variables, these are accessible at any and from any point in your script. As
such their use is frowned upon as it makes it harder to maintain scripts and
control what can be done with data. If you change something about a Global
variable, everything referring to it could break. Often the break that’s been
observed then gets ‘fixed’ and not the root cause… uh oh, as developers and
testers we all know where this scenario can lead.

However,
that general warning aside, there are often good reasons for using Global
variables, especially in small scripts. If we’re putting a simple automation
script together or a game where a hero’s name will remain the same, it could
make sense to use a global variable.

Type or copy
the following into a new .rb file, call it from a CMD window and see what it
does:

# globalVariable_001.rb

# define the Global variable for the
hero's name

$globalHeroName = "Zargon"

# define the method getHeroName

def getHeroName

print "What's the hero called?\n"

heroNameChoice
= gets.chomp

if heroNameChoice == $globalHeroName

puts
"Correct, the hero is called
#{$globalHeroName}! The Orc hugs you!\n"

else

puts
"Oops... that's not the hero's name, the Orc
hits you for 10pts of DMG!\n"

Here we have
a Global variable called $globalHeroName defined in the main body of the
script. Then a method called getHeroName is set up. Within it a nested If statement checks if the
$globalHeroName matches the one the player entered into heroNameChoice (a local
variable). If the variable $globalHeroName wasn’t global, we couldn’t reach it
from the Method, let alone the If statement within the Method. Adequate proof
the variable $globalHeroName really is Global in scope.

As a final
check we added the line puts global_variables.include? :$globalHeroName. This
is asking, do global_variables in
the script include one called $globalHeroName? The answer to which is
true, showing it really is a Global
variable.

To test out
a few assumptions, try making the following changes:

Remove the $ sigil from all instances of $globalHeroName, so there are globalHeroName

The script should now fail as we’ve made the variable a local one, which isn’t available in the Method and If statements.

Now move this local variable into the Method, by
placing it after the Def statement

The script
will work again as the local variable globalHeroName is within the code block
where it’s used. However, you’ll notice the check for it being Global now fails
as we’d expect, give it’s now local in scope.

That’s the
low down on Local and Global variables. Use Global variables with care and do
name all your variables in a meaningful way.