Last active
June 13, 2018 18:39
-
-
Save sumitasok/717ef4fdb8c5f0201b92f40fce8b2383 to your computer and use it in GitHub Desktop.
Understanding the Ruby scopes
This file contains 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
# Class variables with @ are accessible from class methods! | |
class MyClass | |
@var = 2 | |
def self.square | |
@var *= @var | |
end | |
end | |
MyClass.square | |
=> 4 | |
MyClass.square | |
=> 16 |
This file contains 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
# class variables has to be defined using @@. | |
class MyClass | |
@var = 2 | |
def square | |
@var *= @var | |
end | |
end | |
s = MyClass.new | |
s.var | |
=> NoMethodError: undefined method `var' | |
s.square | |
=> NoMethodError: undefined method `*' for nil:NilClass |
This file contains 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
class MyClass | |
@@var = 2 | |
def square | |
@@var *= @@var | |
end | |
def var | |
@@var | |
end | |
end | |
s = MyClass.new | |
s.var | |
=> 2 | |
s.square | |
=> 4 | |
s.var | |
=> 4 | |
c = MyClass.new | |
=> 4 | |
c.square | |
=> 16 | |
c.var | |
=> 16 | |
s.var | |
=> 16 | |
MyClass.y | |
=> exception NoMethodError | |
s.y | |
=> exception NoMethodError |
This file contains 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
class MyGlobal | |
$s = 4 | |
end | |
=> 4 | |
$s | |
=> 4 | |
$s = 7 | |
=> 7 | |
$s | |
=> 7 | |
class MyGlobals | |
def c | |
$s = 12 | |
end | |
end | |
=> :c | |
$s | |
=> 7 | |
MyGlobals.new.c | |
=> 12 | |
$s | |
=> 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment