Variables & Constants
Introduction
Both variables and constants are names associated with references to objects under specific memory addresses.
The difference between variables and constants is that: 1) variables' references are allowed to change during runtime of a Ruby program and constants' references should not change. 2) only constants can be used to reference classes and modules.
Although, a once defined constant's reference to an object should not change during a run time of a Ruby program Ruby does not enforce it.
DEFAULT_CURRENCY = "USD"
DEFAULT_CURRENCY = "EUR" # => warning: already initialized constant DEFAULT_CURRENCY; warning: previous definition of DEFAULT_CURRENCY was here
DEFAULT_CURRENCY # => "EUR"
Naming Rules
Naming variables and constants in Ruby is primarily not about conventions but hard rules.
Variable and constant names in Ruby can use alphanumeric characters and underscores with the reservation that they cannot begin with a number.
Ruby is a case sensitive language. A name of reference starting with a small letter or an underscore is a variable and a name of reference starting with a capital letter is a constant.
# variables
answer = 42 # => 42
an_answer_to_the_universe = 42 # => 42
a1 = "some value" # => "some value"
1a = "some value" # SyntaxError: unexpected tIDENTIFIER, expecting end-of-input
# constants
FavoriteAnimal = "elephant"
FORREST_ANIMALS = ["wolf", "owl", "deer"]
Dynamic Typing
Ruby is a dynamically typed language. This means that in Ruby the type (i.e. Integer, String, Array) of a variable is allowed to change during the runtime of a Ruby program.
Variable Scopes
A variable in Ruby is defined within a scope i.e. an area within which the variable exists. Two variables defined in two different scopes are different non-conflicting entities that are being defined, changed and used separately from each other.
A variable scope is being set through use of special identifiers - sigils. A variable without a sigil e.g. an_animal
is a local variable. A variable starting with @
e.g. @an_animal
is an instance variable. A variable starting with @@
e.g. @@forrest_animals
is a class variable. Finally, a variable starting with $
e.g. $zoo
is a global variable.
Local & Global Variables
A local variable exists only within a local scope i.e. a scope of a method, a block or a module. An instance variable exists within a scope of an instance of some class. A class variable exists within a scope of a class and is therefore available to all its instances. A global variable exists in the global scope and is available everywhere in a Ruby program.