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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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:
On the other hand, class methods are invoked only through the constant refering to the Class object.
Eg:
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
On the other hand, class methods are invoked only through the constant refering to the Class object.
Eg:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
No comments:
Post a Comment