Created
June 15, 2012 16:16
-
-
Save bcamarda/2937346 to your computer and use it in GitHub Desktop.
Explanation of scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# VARIABLE SCOPE | |
=Begin | |
$example A global variable | |
@example An instance variable | |
example A local variable | |
Example A constant | |
@@example A class variable | |
"nil" and "self" cannot be assigned values | |
=End | |
$global = 10 | |
defined? $global | |
#LOCAL | |
1.9.3p194 :008 > def add(num1, num2) | |
1.9.3p194 :009?> num1 + num2 | |
1.9.3p194 :010?> end | |
=> nil | |
1.9.3p194 :011 > add(2,2) | |
=> 4 | |
1.9.3p194 :012 > num1 | |
NameError: undefined local variable or method `num1' for main:Object | |
from (irb#1):12 | |
#GLOBAL | |
#Global variables can be accessed AND CHANGED from anywhere in the program. Strongly discouraged. | |
1.9.3p194 :013 > $0 | |
=> "irb" | |
gets | |
A Job | |
=> "A Job\n" | |
1.9.3p194 :002 > $_ | |
=> "A Job\n" | |
1.9.3p194 :003 > a = 4+4 | |
=> 8 | |
1.9.3p194 :004 > $_ | |
=> "A Job\n" | |
#CLASS | |
1.9.3p194 :001 > class Polygon | |
1.9.3p194 :002?> @@sides = 10 | |
1.9.3p194 :003?> def self.sides | |
1.9.3p194 :004?> @@sides | |
1.9.3p194 :005?> end | |
1.9.3p194 :006?> end | |
=> nil | |
1.9.3p194 :007 > | |
1.9.3p194 :008 > puts Polygon.sides | |
10 | |
=> nil | |
1.9.3p194 :009 > class Triangle < Polygon | |
1.9.3p194 :010?> @@sides = 3 | |
1.9.3p194 :011?> end | |
=> 3 | |
1.9.3p194 :012 > puts Triangle.sides | |
3 | |
=> nil | |
1.9.3p194 :013 > puts Polygon.sides | |
3 | |
=> nil | |
#INSTANCE | |
1.9.3p194 :014 > class Polygon | |
1.9.3p194 :015?> @sides = 10 | |
1.9.3p194 :016?> end | |
=> 10 | |
1.9.3p194 :017 > puts Polygon.class_variables | |
@@sides | |
=> nil | |
1.9.3p194 :018 > puts Polygon.instance_variables | |
@sides | |
=> nil | |
#CONSTANT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment