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 に答える