Skip to content

Instantly share code, notes, and snippets.

@s-andringa
Created August 31, 2009 12:17
Show Gist options
  • Save s-andringa/178424 to your computer and use it in GitHub Desktop.
Save s-andringa/178424 to your computer and use it in GitHub Desktop.
class Object
def metaclass
class << self; self; end
end
end
# - Normal cases -
class Foo
@@bar = 0
def self.set_bar(x)
@@bar = x
end
end
p Foo.send(:class_variable_get, :@@bar) # => 0
Foo.set_bar(5)
p Foo.send(:class_variable_get, :@@bar) # => 5
# --
class Foo; end
def Foo.set_bar(x)
@@bar = x
end
p Foo.send(:class_variable_get, :@@bar) rescue nil # => nil (NameError)
Foo.set_bar(5)
p Foo.send(:class_variable_get, :@@bar) # => 5
p Foo.metaclass.send(:class_variable_get, :@@bar) # => 5
# - Strange case -
class Foo
@@bar = 0
end
def Foo.set_bar(x)
@@bar = x
end
p Foo.send(:class_variable_get, :@@bar) # => 0
Foo.set_bar(5)
p Foo.send(:class_variable_get, :@@bar) # => 0
p Foo.metaclass.send(:class_variable_get, :@@bar) # => 5
# - Work-around -
class Foo
@@bar = 0
end
def Foo.set_bar(x)
class_variable_set(:@@bar, x)
end
p Foo.send(:class_variable_get, :@@bar) # => 0
Foo.set_bar(5)
p Foo.send(:class_variable_get, :@@bar) # => 5
p Foo.metaclass.send(:class_variable_get, :@@bar) rescue nil # => nil (NameError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment