Overloading
Method overloading in programing refers to invoking different behavior of a method of class depending on its arguments. Making it simpler, you can say that a class can have more then one method with the same name, but with different argument i,e different signature of the method.
You can implement different signature of method in any of the below way:
1 : Arguments with different data types, eg: method(int a, int b) method(string a, string b)
2: Variable number of arguments, eg: method(a) vs method(a, b)
class Person
def print_details(name)
"Hey My Name is #{name}"
end
def print_details(name,age)
"Hey My Name is #{name} and #{age}"
end
end
person1 = Person.new
puts person1.print_details("Rajkumar")
puts person1.print_details("Rajkumar",25)
print_details’: wrong number of arguments (1 for 2) (ArgumentError)
So, you can see that, overloading not happening here. ruby expecting print_details to have two argument, but since in the first call, you passed only one argument, it throws error. So we can say that:Ruby do not support method overloading
In ruby there can be only one method with a given name. If there is multiple methods with the same name,the last one prevail i,e the last method will be invoked when called.
Overriding
In object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.
class A
def a
puts 'In class A'
end
end
class B < A
def a
puts 'In class B'
end
end
b = B.new
b.a #In class B