Variable Scope

This week we focused very heavily on ruby variable scopes. So, I thought it would be a good idea to talk about the different variables and their scopes. Scopes are defined as where the variables are accessed within the program.

Here are a list of variables in ruby: -Local(variable)

-Global($variable)

-Class(@@variable)

-Instance(@variable)

-Constant(VARIABLE)

Here are the scopes of each variable within ruby:

-Local: Local variables have a scope within the code construct that they sit in. ie a method or block. Local variables must begin with either an underscore or a lower case letter.

-Global: Global variables are accessible anywhere within the ruby program. Global variables are declared with a ($) before the variable name.

-Class: Class variables are shared with all instances of a specific class.

-Instance: Instance variables are local to specific instances of a specific class.

-Constants: Constants are variables that when a value is declared with constant, that value cannot be changed within the ruby program. If the constant is declared outside of the class, the constant variable is treated with global scope as described in global variables above.

With this basic knowledge of ruby variables and how their scope works, I hope you can now correctly scope variables within your ruby program. In the meantime, I'll be practicing ruby!

-Scott