Given an instance of a Ruby object, how do I get its metaclass?

Usually I can get a metaclass for a specific instance of a Ruby object with something like this:

class C def metaclass class << self; self; end end end # This is this instance metaclass. C.new.metaclass => #<Class:#<C:0x01234567>> # Successive invocations will have different metaclasses, # since they're different instances. C.new.metaclass => #<Class:#<C:0x01233...>> C.new.metaclass => #<Class:#<C:0x01232...>> C.new.metaclass => #<Class:#<C:0x01231...>> 

Say I just want to know the metaclass of an arbitrary instance of an obj object of an arbitrary class, and I don't want to define a metaclass method (or similar) for the obj class.

Is there any way to do this?

+3
source share
2 answers

Yes.

metaclass = class << obj; self; end

+6
source

The official name is singleton_class . The way to get it (in Ruby 1.9.2) is simple:

 obj.singleton_class 

For older versions of Ruby, you can use backports :

 require 'backports/1.9.2/kernel/singleton_class' obj.singleton_class # or without using backports: class << obj; self; end 
+10
source

Source: https://habr.com/ru/post/894996/


All Articles