15 March 2015
Ruby Variables
Ruby has 5 main variable types: Global Variables, Constants, Class Variables, Instance Variables, and Local Variables.
As you begin to design programs, the most important thing to consider when deciding what sort of variable to use is scope, or where in your program you want a variable to be accessible.
Global Variables (Ex. $global_variable = 100
)
These are easy to tell apart because they always begin with a $. Global variables, as their name suggests, can be accessed from anywhere within your program. Consequently, they need to be used sparingly and careful thought should always be made before using a global variable. If you ever run into trouble, global variables can make it difficult to isolate a bug, because their scope is the entirety of a program. Whether you define a global variable separately, in a class, or in module, its scope will encompass everything! Global variables should not change, however, Ruby will allow you to reassign them but will also prompt you that you are doing something very risky.
Constants (Ex. HOURS_IN_DAY = 24
)
Constants are similar to global variables but their scope is slightly more limited. Constants always start with a capital letter and as their name suggests, you should not expect a constant's value to change, though Ruby will allow you to change them with a warning. Unlike global variables, the scope of a constant depends on where it is defined. Constants may be initialized within a class or module, in which case they can be accessed only within said class or module. Or they may also be defined outside of a class or module entirely, in which case their scope becomes global. They may NOT be defined within a method.
Class Variables (Ex. @@types_of_cars = 12
)
Class variables always start with @@ and as their name suggests, have a scope that is limited to the class in which they are defined. They must be initialized before they can be used in any methods of a class, which means they are usually defined immediately after your class. A key distinction of class variables has to do with inheritance. When you define a class variable, you are setting it for a superclass and any subclasses that should result from that superclass.
Instance Variables (Ex. @type_of_cars = 12
)
Instance variables are similar to class variables but they always begin with a single @. Unlike class variables, instance variables ARE defined within methods and can then be used within any instance of their class. The value of an instance variable can be changed easily, but if an instance variable is used in a number of places in the same class, it can cause unexpected bugs when changes are made.
Local Variables (Ex. x = 12
)
Local variables have the smallest scope in Ruby, as their scope is limited to where they are defined. They are written in all lower case letters and are typically defined and used in a single method or block, though they can also be initialized to have a larger scope as well.
Prev | Next |