Created
January 14, 2016 09:05
-
-
Save ngtk/562427a829515e0c5f0a to your computer and use it in GitHub Desktop.
Singleton Class
This file contains hidden or 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
| puts <<-EOL | |
| 1. finding method | |
| EOL | |
| class C | |
| def a_method | |
| 'C#a_method' | |
| end | |
| end | |
| class D < C | |
| end | |
| obj = D.new | |
| puts obj.a_method # => "C#a_method" | |
| puts <<-EOL | |
| 1. superclass of singleton class | |
| EOL | |
| obj = D.new | |
| class << obj | |
| def a_singleton_method | |
| 'obj#a_singleton_method' | |
| end | |
| end | |
| puts obj.a_singleton_method # => "obj#a_singleton_method" | |
| puts obj.singleton_class.superclass # => D | |
| puts <<-EOL | |
| 3. singleton class | |
| EOL | |
| class C | |
| class << self # self is C | |
| def a_class_method # a.k.a) a_singleton_method | |
| 'C.a_class_method' | |
| end | |
| end | |
| end | |
| puts C.a_class_method # => "C.a_class_method" | |
| puts C.singleton_class # => #<Class:C> | |
| puts D.singleton_class # => #<Class:D> | |
| puts D.singleton_class.superclass # => #<Class:C> | |
| puts C.singleton_class.superclass # => #<Class:Object> | |
| puts D.singleton_class.ancestors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment