Ruby Variables
Ruby has a number of different types of variables that are available to us. Five to be specific. I find a list helpful to assist me in remembering when to use which one and when I shouldn’t, so I hope it’s helpful to you also.
Local Variables
-A local variable has a name starting with a lower case letter or an underscore character (_
). Local variables do not, like globals and instance variables, have the value nil
before initialization
Instance Variables
-Instance variables begin with @
. Uninitialized instance variables have the value nil
Class Variable
-Class variables begin with @@
and must be initialized before they can be used in method definitions.
- Class variables are shared among descendants of the class or module in which the class variables are defined. -Referencing an uninitialized class variable produces an error
.
Global Variables
-Global variables begin with $
. Uninitialized global variables have the value nil
-Assignment to global variables alters global status. It is not recommended to use global variables.
Constants
-Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally
-Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.
We’ve now gone over each type of ruby variable available to us, I hope this helps you know the difference between each! Thanks for reading, happy coding!