我们为什么要在Ruby的类中放入模块? [英] Why would we put a module inside a class in Ruby?

查看:99
本文介绍了我们为什么要在Ruby的类中放入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,我发现为了命名空间而将类放在模块中可能会很有用.我还看到可以将模块放入类中.但是我不明白你为什么要这么做.

In Ruby, I see that it can be useful to put classes inside modules for the sake of namespacing. I also see that it's possible to put modules inside classes. But I don't see why you'd do that.

模块通常混入类中,对吧?那么,在类中定义模块的目的是什么?

Modules are generally mixed into classes, right? So, what would be the purpose of defining a module inside a class?

推荐答案

我们在编写类似猿的代码时可以使用它:

We could use it when writing ape-like code like this:

class DrugDealer
  module Drug
    def happy?; true; end
  end

  def approach(victim)
    victim.extend Drug
  end
end

o = Object.new
DrugDealer.new.approach(o)
o.happy? # => true


在现实世界中更实用的另一个示例是让混合包仅由子类应用.


Another example that would be more practical in the real world is to have mixins that are only applied by subclasses.

当某事物的某些方面适用于某些子类而其他方面适用于其他子类时,这很有用,而这些方面的应用顺序不足以为清晰的类层次结构让路(树).考虑多重继承!简化示例:

This is useful when some facets of a thing apply to some subclasses and other facets apply to other subclasses, without there being enough order in the way these aspects apply to make way for a clear class hierarchy (tree). Think multiple inheritance! A simplified example:

class Person
  def handshake
    :sloppy
  end

  def mind_contents
    :spam
  end

  module Proper
    def handshake
      :firm
    end
  end

  module Clever
    def mind_contents
      :theories
    end
  end
end

class Professor < Person
  include Proper
  include Clever

  # ...
end

以此类推.明智地使用时,有点不错.甚至超级调用和构造函数(尽管我在这里都没有定义)也以我希望它们的方式流过所有的mixin和类.

And so on. Kind of nice, when used sensibly. Even super calls and constructors (I didn't define any here though) flow through all the mixins and classes the way I want them to.

这篇关于我们为什么要在Ruby的类中放入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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