user3963226
user3963226

Reputation:

Modules and multiple inheritance in ruby on rails?

I learn modules behave as a multiple inheritance in ruby on rails. I saw an example which I understand but what if two modules have same methods then which one call?

module A
  def a1
  end

  def a2
  end
end

module B
  def a1
  end

  def b2
  end
end

class Sample
  include A
  include B

  def s1
  end
end

samp=Sample.new
samp.a1
samp.a1

Upvotes: 1

Views: 4168

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

Ruby does not have multiple inheritance. Ruby has something similar called mixins which can be implemented using Modules.

Mixins are not multiple inheritance, but instead mostly eliminate the need for it.

To answer your question, when you include two modules in a class and both of them has the method with same name (in your case, method a), in that case, a method from the 2nd (the last one) Module will be called.

module A
  def a1
    puts "I am defined in A"
  end

  def a2
  end
end

module B
  def a1
    puts "I am defined in B"
  end

  def b2
  end
end

class Sample
  include A
  include B

  def s1
  end
end

samp = Sample.new
puts samp.a1
# I am defined in B

Why and How?

When a module M is included in a class C, an anonymous proxy class ⟦M′⟧ (called an include class) is created such that its method table pointer points to M's method table. (Same for the constant table and module variables.) ⟦M′⟧'s superclass is set to C's superclass and C's superclass is set to ⟦M′⟧.

Also, if M includes other modules, the process is applied recursively.

puts Sample.ancestors.inspect
# [Sample, B, A, Object, Kernel, BasicObject]

It becomes more clear when you inspect the ancestors of the Sample class. See the order here. When a method is called, Ruby looks for the method definition first in Sample class itself, but doesn't find it. Then, it looks for the a method in B and it finds it and calls it.

Hope it is clear to you now.

Upvotes: 4

Simone Carletti
Simone Carletti

Reputation: 176352

The last wins. In your example (that you could have tried on your own running it on the console with a print statement) the a1 method that will be called is the one defined in B.

Upvotes: 0

Related Questions