Skip to content

Instantly share code, notes, and snippets.

@sumitasok
Last active June 13, 2018 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumitasok/717ef4fdb8c5f0201b92f40fce8b2383 to your computer and use it in GitHub Desktop.
Save sumitasok/717ef4fdb8c5f0201b92f40fce8b2383 to your computer and use it in GitHub Desktop.
Understanding the Ruby scopes
# 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
# 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
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
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