How do I get the class of a BasicObject instance?

后端 未结 8 2057
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2020-12-08 03:32

    This is my modification of @paon's answer:

    Reasoning behind the changes:

    • Method name doesn't clash with existing libs, e.g. the ActiveSupport::Duration instance behavior 2.seconds.class remains Fixnum.
    • Since Object doesn't have its own __realclass__ method, we want to avoid allocating the eigenclass for those instances. @paon's original answer did this inherently by defining the class method name.

    class BasicObject
      def __realclass__
        ::Object === self ?
          # Note: to be paranoid about Object instances, we could 
          # use Object.instance_method(:class).bind(s).call.
          self.class :
          (class << self; self end).superclass
      end
    end
    
    # test
    require 'active_support/core_ext/integer'
    require 'active_support/core_ext/numeric'
    
    duration = 2.seconds
    string = 'hello world'
    p duration.class  # => Fixnum
    p string.class    # => String
    GC.start
    p ObjectSpace.count_objects[:T_CLASS]  # => 566
    
    # creates the eigenclass
    p duration.__realclass__  # => ActiveSupport::Duration
    p ObjectSpace.count_objects[:T_CLASS]  # => 567
    
    # doesn't create the eigenclass
    p string.__realclass__  # => String
    p ObjectSpace.count_objects[:T_CLASS]  # => 567
    

提交回复
热议问题