Signup/Sign In

Types of Variables in Ruby

There are 4 different types of variables in Ruby. They are :

  1. Local Variables
  2. Class Variables
  3. Instance Variables
  4. Global Variables
Local Global Instance Class
Scope Only within the block or a function Throughout the program Limited to one particular instance of a class Limited to the class that they are defined in
Naming Local variables begin with a lowercase letter or _(underscore) Global variables begin with $ Instance variables begin with @ Class variables begin with @@
Initialization Not necessary to initialize. Using uninitialized local variable is interpreted as call to a method that has no arguments. Not necessary to initialize. Uninitialized global variables have nil value. Not necessary to initialize. Uninitialized instance variables have nil value. Must be initialized before they are used. Using uninitialized class variable results in error.