Created
March 24, 2009 16:50
-
-
Save hukl/84205 to your computer and use it in GitHub Desktop.
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 Object | |
def metaclass | |
class << self; self; end | |
end | |
end | |
class Foo | |
def self.hello | |
puts "hello" | |
end | |
end | |
class Bar < Foo | |
def self.goodbye | |
puts "goodbye" | |
end | |
end | |
# In Ruby, classes are objects. Class methods are singleton methods of the | |
# class object. | |
p Bar.object_id | |
# => 59030 | |
p Bar.singleton_methods.sort | |
# => ["goodbye", "hello"] | |
# But they are not defined on the class object itself - they instance methods | |
# of the classes eigenclass/metaclass | |
p Bar.metaclass.instance_methods.sort - Class.instance_methods | |
# => ["goodbye", "hello"] | |
# You can also define singleton methods on "regular" objects | |
s = "hello I'm a String" | |
class << s; def random_method; self.split("").sort_by{ rand }.join;end;end | |
p s.random_method | |
# => "tea'Smi nr o llgIh" | |
p s.singleton_methods | |
# => ["random_method"] | |
p s.metaclass.instance_methods.sort - String.instance_methods | |
# => ["random_method"] | |
# So this works just as with classes basically. Objects and classes have | |
# metaclasses because they are both objects. The only difference is that | |
# classes can be inherited and so it is possible to reach into the superclasses | |
# metaclass | |
p Bar.superclass.metaclass.instance_methods.sort - Class.instance_methods | |
# => ["hello"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment