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

两盒软妹~` 提交于 2019-12-10 15:59:53

问题


Normally, I might get the metaclass for a particular instance of a Ruby object with something like this:

class C
  def metaclass
    class << self; self; end
  end
end

# This is this instance's 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...>>

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

Is there a way to do that?


回答1:


Yep.

metaclass = class << obj; self; end




回答2:


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

obj.singleton_class

For older Ruby versions, you can use backports:

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


来源:https://stackoverflow.com/questions/2945830/given-an-instance-of-a-ruby-object-how-do-i-get-its-metaclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!