Ruby Variables

Introduction

A variable springs into existence as soon as the interpreter sees an assignment to that variable.

Scope

Global Scope

Scope that covers the entire program. Global variables start with a dollar-sign ($).

Local Scope

  • The top level (outside of all definition blocks) has its own local scope.
  • Every class or module definition block (class, module) has its own local scope, even nested class/module definition blocks.
  • Every method definition (def) has its own local scope.

Rules about Naming

  • A local variable (declared within an object) name consists of a lowercase letter (or an underscore) followed by name characters (sunil, _z, hit_and_run).
  • An instance variable (declared within an object always "belongs to" whatever object self refers to) name starts with an ''at'' sign (''@'') followed by a name (@sign, @_, @Counter).
  • A class variable (declared within a class) name starts with two ''at'' signs ('''') followed by a name (sign, _, Counter). A class variable is shared among all objects of a class. Only one copy of a particular class variable exists for a given class. Class variables used at the top level are defined in Object and behave like global variables. These are rarely used in Ruby programs.
  • Global variables start with a dollar sign (''$'') followed by name characters. A global variable name can be formed using ''$-'' followed by any single character ($counter, $COUNTER, $-x). Ruby defines a number of global variables that include other punctuation characters, such as $_ and $-K.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.