Sunday, January 7, 2007

Ruby singleton class

In ruby world singleton class is term used frequently to describe something that is in java world called anonymous class. The term is sometime very confusing. I have seen this technique being used to extend class's behavior (as instance of Class). Suppose that we need to define a class instance variable the variable associated with the class (different from class variable, which is global variable)
class Foo
end
class Foo
  class << self
    attr_accessor :instances
  end
end
the equivalent variant of above code is
class Foo
end
class_foo = Foo
class << class_foo
    attr_accessor :instances
end
now do some test
Foo.instances =[] #=>[]
Foo.instance_variables #=>[@instances]
Foo.class_variables #=>[]
Foo.instances << Foo.new #=> [#<Foo:0x8241cbc>]
class Foo
  @@total = 0
end
Foo.class_variables #=>["@@total"]
The great tutorial about ruby singleton class can be found here

No comments: