Method Overload in Ruby

Ruby does not allow writing of another method with the same name. So, overloading is not possible in Ruby. However, you can be crafty in a way of overloading a method by utilizing and extending with new logic within an existing method.

For instance, you want to change how one class handles parameter.

Class MyClass
 def initialize(*args)
 case
  when 2
   @var1, @val2 = *args
  when 3
    @var1, @var2, @var3 = *args
  else
    raise ArgumentError, “This is an error to have more than three and less than two arguments”
 end
end

Create an instances with this class can be done in the following manger without too much troubles

MyClass.new(1,2) //OK
MyClass.new(1,2,3) //OK
MyClass.new //produces an error message

We could have added Duck Type checking to this class above for more elegant code as well. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…