本文介绍了给定Ruby对象的实例,如何获取其元类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,我可能会获得像这样的Ruby对象的特定实例的元类:
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...>>
比方说,我只想知道任意类的任意对象实例obj
的元类,并且我不想在obj
的类上定义metaclass
(或类似的)方法.
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
.
有办法吗?
推荐答案
是的.
metaclass = class << obj; self; end
这篇关于给定Ruby对象的实例,如何获取其元类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!