Classes and Modules

From RubySpec

Jump to: navigation, search

Singleton classes

When doing certain kinds of meta-programming, it can be very useful to easily get hold of the class instance where singleton methods are defined. There exists an RCR with number #231 for this purpose. It defines a method in Kernel that looks like this:

module Kernel
  def singleton_class
    class << self; self; end
  end
end

which would allow you to evaluate blocks in the context of the singleton class:

obj.singleton_class.class_eval do 
  def test
    $stderr.puts self
  end
end
Personal tools