在Object中的模块中混合会导致所有对象将该模块的实例方法作为单例方法继承 [英] Mixing in a module within Object causes all Objects to inherit that module's instance methods as singleton methods

查看:135
本文介绍了在Object中的模块中混合会导致所有对象将该模块的实例方法作为单例方法继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将自己的行为添加到 Object 类时,我会得到在将模块混合到用户定义的类时不会发生的不良影响。

When attempting to add my own behavior to the Object class, I get undesired effects that don't occur when mixing the module into a user-defined class.

module Entity
  def some_instance_method
    puts 'foo'
  end

  def self.secret_class_method
    puts 'secret'
  end

  module ClassMethods
    def some_class_method
      puts 'bar'
    end
  end

  def self.included( other_mod )
    other_mod.extend( ClassMethods )
  end
end

现在,我创建了类 Bob ,使其包含实体

Now, I create class Bob such that it includes Entity.

class Bob; include Entity; end;

这产生了期望和预期的输出:

This yields the desired and expected output:

Bob.secret_class_method       #=> NoMethodError
Bob.some_instance_method      #=> NoMethodError
Bob.some_class_method         #=> bar
Bob.new.secret_class_method   #=> NoMethodError
Bob.new.some_instance_method  #=> foo
Bob.new.some_class_method     #=> NoMethodError

但是如果不是定义类 Bob 我打开了类对象并包含实体,如下所示:

But if instead of defining class Bob I were to open up class Object and include Entity like so:

class Object; include Entity; end

然后我看到的输出是:

Object.secret_class_method        #=> NoMethodError
Object.some_instance_method       #=> foo
Object.some_class_method          #=> bar
Object.new.secret_class_method    #=> NoMethodError
Object.new.some_instance_method   #=> foo
Object.new.some_class_method      #=> NoMethodError

如果我然后定义类 Bob ,它的行为方式相同: some_instance_method 可以在类 Bob 上调用。似乎关于 Object 类本身的某些内容正在弄乱这个模式的行为,否则我只是在这里做错了。有人可以解释这个奇怪的行为吗?我不希望我的所有 Object 都将实例方法作为单例方法继承!

If I then define class Bob, it behaves in the same way: some_instance_method can be called on class Bob. It seems as though something about the Object class itself is messing with the behavior of this pattern, or else I'm just doing something wrong here. Can someone please explain this odd behavior? I don't want all my Objects to inherit instance methods as singleton methods as well!

推荐答案

Bob ia是一个对象(更确切地说: Bob 是一个<$ c $的实例c> Class ,它是 Module 的子类,它是 Object 的子类,这是 Entity 的子类,因此它有 Entity 的方法。这就是继承的工作原理。

Bob ia an object (more precisely: Bob is an instance of Class, which is a subclass of Module which is a subclass of Object, which is a subclass of Entity), therefore it has Entity's methods. That's just how inheritance works.

这篇关于在Object中的模块中混合会导致所有对象将该模块的实例方法作为单例方法继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆