steven_noble
steven_noble

Reputation: 4203

Including two Ruby mixins with the same method name

What's going on with this:

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?

Upvotes: 4

Views: 1242

Answers (1)

tadman
tadman

Reputation: 211560

Once you've included a module, I'm not sure it will be included again. It will probably be listed as already included so the duplicate operation is ignored.

If you need to do this, which would be very strange indeed, you probably need to fake out Ruby by making a module, even a temporary one, that includes your target module, then include that one instead.

Upvotes: 2

Related Questions