Ruby Variables

Local Variables

A local variable has a local scope or context. If defined within a method, its scope is kept within that method.

  • Local variables must begin with either a lowercase letter or an underscore (_)
  • Must not be prefixed with @, @@, or $ because they are reserved for other types of variables

Instance Variables

An instance variable belongs to a particular instance of class. It can only be accessed from outside that instance via an accessor method.

  • Instance variables are always prefixed with a single at sign (@) [Example: @hello]

Class Variables

A class variable is shared among all instances of a class. Only one copy of a class variable exists for a given class.

  • It is prefixed by two at signs (@@) [Example @@times]
  • You have to initialize (declare a value for) a class variable before you use it.

Global Variables

Global variables are globally available to a program, inside any structure. Their scope is the whole program.

  • They are prefixed by a dollar sign ($) [Example $amount]

Also published on Medium.

 

austinvernsonger