How do I get the class of a BasicObject instance?

后端 未结 8 2086
小鲜肉
小鲜肉 2020-12-08 03:03

I have a script that iterates using ObjectSpace#each_object with no args. Then it prints how many instances exist for each class.

I realized that some

8条回答
  •  渐次进展
    2020-12-08 03:31

    fguillen's link made me think of this way.

    Pros:

    1. It doesn't need external libraries.

    Cons:

    1. It must be executed before loading any classes that subclass BasicObject.
    2. It adds a method to every new class

    .

    class BasicObject
      def self.inherited(klass)
        klass.send(:define_method, :__realclass__) { klass }
      end
      def __realclass__
        BasicObject
      end
    end
    
    # ensures that every Object will also have this method
    class Object
      def __realclass__
        Object.instance_method(:class).bind(self).call
      end
    end
    
    require 'active_support/core_ext'
    
    20.seconds.__realclass__  # => ActiveSupport::Duration
    
    # this doesn't raise errors, so it looks like all objects respond to our method
    ObjectSpace.each_object{|e| e.__realclass__ }
    

提交回复
热议问题