Ruby 2 Overloading Methods

You want to create two different versions of a method with the same name: two methods that differ in the arguments they take. However, a Ruby class can have only one method with a given name (if you define a method with the same name twice, the latter method definition prevails as seen in example p038or.rb in topic Ruby Overriding Method). Within that single method, though, you can put logic that branches depending on how many and what kinds of objects were passed in as arguments.
Here's a Rectangle class that represents a rectangular shape on a grid. You can instantiate a Rectangle by one of two ways: by passing in the coordinates of its top-left and bottom-right corners, or by passing in its top-left corner along with its length and width. There's only one initialize method, but you can act as though there were two.
  1. # The Rectangle constructor accepts arguments in either  
  2. # of the following forms:  
  3. #   Rectangle.new([x_top, y_left], length, width)  
  4. #   Rectangle.new([x_top, y_left], [x_bottom, y_right])  
  5. class Rectangle  
  6.   def initialize(*args)  
  7.     if args.size < 2  || args.size > 3  
  8.       # modify this to raise exception, later  
  9.       puts 'This method takes either 2 or 3 arguments'  
  10.     else  
  11.       if args.size == 2  
  12.         puts 'Two arguments'  
  13.       else  
  14.         puts 'Three arguments'  
  15.       end  
  16.     end  
  17.   end  
  18. end  
  19. Rectangle.new([10, 23], 4, 10)  
  20. Rectangle.new([10, 23], [14, 13])  
The above program p037rectangle.rb is incomplete from the Rectangle class viewpoint, but is enough to demonstrate how method overloading can be achieved. Also remember that the initialize method takes in a variable number of arguments.