Open In App

Method Overloading In Ruby

What is method overloading?
Method overloading is a feature that allows a class to have more than one method with same name but different method signature ie. different number of arguments, order of arguments and different types of parameters. Return type is not included in method signature, thus overloaded methods can have different return type. Method overloading is an example of static binding or compile time polymorphism.



Ruby does not support method overloading
Method overloading is a feature of statically typed language in which binding of methods takes place during compile time. But Ruby being a dynamically typed language, it does not support static binding at all. Also it is difficult to determine which method will be invoked in case of dynamic argument-based dispatch in a language with optional arguments and variable-length argument lists. In addition, the implementing language of Ruby is C which itself does not support method overloading. The most recent version of the method is considered while ignoring the previously defined versions of the method.
Example below shows Ruby does not support usual approach of method overloading
Example #1:




class Test
    def self.sum(a,b)
        puts(a+b)
    end
    def self.sum(a,b,c)
        puts(a+b+c)
    end
      
end
Test.sum(1,2)

Output:



main.rb:13:in `sum': wrong number of arguments (2 for 3) (ArgumentError)                                                      
        from main.rb:18:in `
'

In Ruby, when a second method is defined with the same name it completely overrides the previously existing method. The previous method is no longer accessible and hence throws error when we try to access it.

Example #2:




class Test
    def self.sum(a,b)
        puts(a+b)
    end
    def self.sum(a,b,c)
        puts(a+b+c)
    end
      
end
Test.sum(1,2,7)

Output:

10

The second method overwrites the previous method and hence it works absolutely fine when we call the method with three arguments.
 
Implementing method overloading in Ruby
A possible approach to implement overloading in Ruby can be by varying the number of arguments of the method. However, overloading methods using different types of arguments is possible but it becomes really difficult to keep a trace of the code.Both the approaches are demonstrated below:
Method overloading by varying the number of arguments


Article Tags :