给定一个Ruby对象的实例,我如何获得它的元类?

时间:2010-05-31 20:27:28

标签: ruby metaprogramming metaclass singleton

通常,我可能会得到类似于Ruby对象的特定实例的元类:

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...>>

假设我只想知道任意类的任意对象实例obj的元类,并且我不想在类的上定义metaclass(或类似)方法。 obj

有办法吗?

2 个答案:

答案 0 :(得分:11)

官方名称为singleton_class。获得它的方法(在Ruby 1.9.2中)就是:

obj.singleton_class

对于较旧的Ruby版本,您可以使用backports

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

答案 1 :(得分:7)

是的。

metaclass = class << obj; self; end