Search code examples
rubydelegation

What is delegation in Ruby?


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?


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.