【问题标题】:Can a Ruby object have multiple eigenclasses?一个 Ruby 对象可以有多个特征类吗?
【发布时间】:2017-06-17 23:50:21
【问题描述】:

特征类被添加到继承层次结构中。

如果添加了多个单例方法,这些方法是添加到同一个特征类中,还是注入到该对象的继承层次结构中的不同特征类中?

例如

def foo.test
  0
end
def foo.test2
  0
end

这是否会添加 2 个特征类:一个带有“test”方法,另一个带有“test2”方法?还是一个具有两种方法的特征类?

【问题讨论】:

    标签: ruby eigenclass


    【解决方案1】:

    这些被添加到单个元类中,因为对象总是只有一个单例类

    你可以检查一下:

    foo.singleton_methods
    #=> [:test, :test2]
    foo.method(:test)
    #=> #<Method: #<Object:0x007ff9b4d48388>.test>
    foo.method(:test2)
    #=> #<Method: #<Object:0x007ff9b4d48388>.test2>
    

    或者使用Method#owner:

    foo.method(:test).owner == foo.method(:test2).owner
    #=> true
    

    【讨论】:

    • 整洁!没想到。
    【解决方案2】:

    他们去同一个单例类,这很容易验证自己:

    foo.singleton_class.instance_methods.grep(/test/)
    #=> [:test, :test2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2017-06-28
      • 1970-01-01
      • 2019-11-17
      相关资源
      最近更新 更多