3

这是怎么回事:

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?
4

1 回答 1

2

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

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

于 2012-08-19T05:58:54.440 回答