Ruby Language Accessing Instance/Class Variables in Singleton Classes


Example

Singleton classes share their instance/class variables with their object.

class Example
  @@foo = :example
end

def Example.foo
  class_variable_get :@@foo
end

Example.foo #=> :example

class Example
  def initialize
    @foo = 1
  end

  def foo
    @foo
  end
end

e = Example.new

e.instance_eval <<-BLOCK
  def self.increase_foo
    @foo += 1
  end
BLOCK

e.increase_foo
e.foo #=> 2

Blocks close around their instance/class variables target. Accessing instance or class variables using a block in class_eval or instance_eval isn't possible. Passing a string to class_eval or using class_variable_get works around the problem.

class Foo
  @@foo = :foo
end

class Example
  @@foo = :example 

  Foo.define_singleton_method :foo do
    @@foo
  end
end

Foo.foo #=> :example