包括两个具有相同方法名称的Ruby mixin

时间:2012-08-19 05:55:54

标签: ruby mixins

这是怎么回事:

module Sounds
  def dog
    "bark"
  end
end

module Noises
  def dog
    "woof"
  end
end

class Animals
  include Sounds
  include Noises
end

x = Animals.new
x.dog # Returns "woof", as I expected

class Animals
  include Sounds
end

x.dog # Still returns "woof" for some reason -- shouldn't it be bark?

y = Animals.new
y.dog # Also returns "woof" for some reason -- shouldn't it be bark?

1 个答案:

答案 0 :(得分:2)

一旦你加入了一个模块,我不确定它是否会被再次包含在内。它可能会被列为已包含,因此忽略重复操作。

如果你需要这样做,这确实很奇怪,你可能需要通过创建一个包含目标模块的模块(甚至是一个临时模块)来伪造Ruby,然后再包含那个模块。