Sta*_*rom 4 ruby singleton metaprogramming metaclass
通常,我可能会使用以下内容获取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...>>
Run Code Online (Sandbox Code Playgroud)
假设我只想知道任意类的任意对象实例的元obj类,并且我不想metaclass在类的上定义(或类似)方法obj.
有没有办法做到这一点?
Mar*_*une 11
官方名称是singleton_class.获取它的方法(在Ruby 1.9.2中)很简单:
obj.singleton_class
Run Code Online (Sandbox Code Playgroud)
对于较旧的Ruby版本,您可以使用backports:
require 'backports/1.9.2/kernel/singleton_class'
obj.singleton_class
# or without using backports:
class << obj; self; end
Run Code Online (Sandbox Code Playgroud)