Question

I came across this in my textbook, but I don't even know what delegation is. I know what inclusion is, but not what delegation is.

In the context of Ruby, compare delegation to module inclusion in terms of the notion of class interfaces.

With module inclusion, methods defined in modules become part of the interface of classes(and all their subclasses). This is not the case with delegations.

Can you explain in layman's terms?

Was it helpful?

Solution

Delegation is, simply put, is when one object uses another object for a method's invocation.

If you have something like this:

class A
  def foo
    puts "foo"
  end
end

class B
  def initialize
    @a = A.new
  end

  def bar
    puts "bar"
  end

  def foo
    @a.foo
  end
end

An instance of the B class will utilize the A class's foo method when its foo method is called. The instance of B delegates the foo method to the A class, in other words.

OTHER TIPS

class A
  def answer_to(q)
    "here is the A's answer to question: #{q}"
  end
end

class B
  def initialize(a)
    @a = a
  end
  def answer_to(q)
    @a.answer_to q
  end
end

b = B.new(A.new)

p b.answer_to("Q?")


module AA
  def answer_to(q)
    "here is the AA's answer to question: #{q}"
  end
end

class BB
  include AA
end

p BB.new.answer_to("Q?")

B delegate the question to A, while BB use module AA to answer question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top