sumitasok
6/13/2018 - 5:48 PM

ruby-scopes.rb

Understanding the Ruby scopes

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
# 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