Skip to content

Instantly share code, notes, and snippets.

Created Mar 24, 2009
What would you like to do?
class Object
def metaclass
class << self; self; end
class Foo
def self.hello
puts "hello"
class Bar < Foo
def self.goodbye
puts "goodbye"
# 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