Accessing Instance and Class Variables in Singleton Classes
suggest changeSingleton methods can access class variables of the class they are defined on:
class Example
@@foo = :example
def self.foo
class_variable_get(:@@foo)
end
end
Example.foo # => :example
An object's singleton methods can also access that object's instance variables:
class Example
def initialize
@foo = 1
end
attr_reader :foo
end
example = Example.new
def example.increase_foo
@foo += 1
end
example.increase_foo
example.foo # => 2
Blocks close over local variables from the scope where they are defined. In an instance_eval or class_eval block, instance variables follow self, but class variables are resolved lexically and may not belong to the receiver. To read the target’s class variables, pass a string to class_eval or call class_variable_get.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents