Scope
In Ruby, variables have a scope that outlines what other variables and methods are available to them versus which ones are not. There are different levels of scope:
- Class-level
- Instance-level
- Global-level
- Local-level
Class-level
Variables defined at the class-level scope are usually marked with @@
. They are available for use anywhere within the class block or any sub-class blocks:
class MyClass@@class_variable = "This is the Class variable"def inner_method"From MyClass: #{@@class_variable}"endendclass SubClass < MyClassdef display_class_variable"From SubClass: #{@@class_variable}"endendclassInstance = MyClass.new()subClassInstance = SubClass.new()puts subClassInstance.display_class_variable# Output: From SubClass: This is the Class variableputs classInstance.inner_method# Output: From MyClass: This is the Class variable
Instance-level
Variables defined at the instance-level scope are usually marked with @
and created within a class’s initialize
method. They are available for whenever an instance of the class if was defined in is used:
class Persondef initialize(name)@name = nameenddef name@nameendendperson = Person.new("Randy")puts person.instance_variables # Output: @nameputs person.name # Output: Randy
Global-level
Variables defined in the global scope can be access anywhere within the Ruby program. Their names start with $
:
$global_number = 42def show_numbersputs [$global_number]endshow_numbers # Output: 42
Local-level
Variables defined at the local scope are the most contextual; whichever block they are defined in usually determines how far their scope reaches.
Below, local_to_outside_method
is local to the general, global scope of the program. Inside the add_numbers()
method is a variable whose scope exists only within the method, local_to_method
:
local_to_outside_method = 32def add_numbers(outside_term)local_to_method = 42outside_term + local_to_methodendputs local_to_outside_method + add_numbers(3) # Output: 77
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.