Ruby 2 Scope

Scope refers to the reach or visibility of variables. Different types of variables have different scoping rules. We'll be talking chiefly about two types: global and local variables.

Global scope and global variables

We're starting with the scope that's used least often, but which you need to be aware of: global scope, meaning scope that covers the entire program. Global scope is enjoyed by global variables. Global variables are distinguished by starting with a dollar-sign ($) character. They are available everywhere in your program. Global variables never go out of scope. However, global variables are used very little by experienced programmers (except perhaps a few of the built-in ones).

Built-in global variables

The Ruby interpreter starts up with a fairly large number of global variables already initialized. These variables store information that's of potential use anywhere and everywhere in your program. For example, the global variable $0contains the name of the file Ruby is executing. The global $: (dollar sign followed by a colon) contains the directories that make up the path Ruby searches when you load an external file. $$ contains the process id of the Ruby process. And there are more.

Local scope

Note: Do not worry if you do not understand this, right now.
You can tell by looking at a Ruby program where the local scopes begin and end, based on a few rules:
  • 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.