Tuesday, February 14, 2012

Singleton class. Singleton method Vs Class method.

Every object is associated with two classes. One is which we can get using class method of object(eg: "hello".class) and the other is called the eigenclass(or singleton class).

The singleton methods of an object are the instance methods of the anonymous eigenclass associated with that object.

To open up an singleton class of an object str, use class << str

Eg:
str = "hello world"
class << str #open singleton class
def m1
puts "singleton method m1 of object str"
end
end
str.singleton_class.instance_methods.include?(:m1) # =>true
view raw singleton.rb hosted with ❤ by GitHub


 Thus, singleton class is an anonymous class associated with every object.


A method added to a single object rather than to a class of objects is known as singleton method. Also the class methods on a class are nothing more than singleton methods on the Class instance that represent that class.

Eg:
class Foo
end
f = Foo.new
def f.print_smth #singleton method
puts "hello world"
end
f.print_smth # => hello world
f1 = Foo.new
f1.print_smth # error : undefined method
view raw singleton.rb hosted with ❤ by GitHub


On the other hand, class methods are invoked only through the constant refering to the Class object.

Eg:
class Bar # Bar is Class instance
def self.hello # class method created using self. Also singleton method of Bar
puts "hello"
end
def Bar.world # class method created using class name. Also singleton method of Bar
puts "world"
end
end
Bar.hello # => hello
Bar.world # => world
view raw singleton.rb hosted with ❤ by GitHub

   

No comments:

Post a Comment