A ruby class can have only one method with the same name. Ruby overrule method if they are defined again.

The number of arguments in a method can be variable. How?

Download Free Ruby Ebook

Example

Method overloading

Create a new object, then you can call a method with 2 or 3 arguments.

1
2
3
a = Example.new
a.hello('Thomas')
a.hello('Thomas','Edison')

This works because internally it checks the number of arguments with an if statement.

Method overloading is defined inside the class definition.

In the method hello, pass the arguments (*args). Then validate with an if statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Example
def hello(*args)
if args.size < 1 || args.size > 2
raise 'Method takes 1 or 2 arguments'
else
if args.size == 1
puts "Hello #{args[0]}"
else
puts "Hello #{args[0]} #{args[1]}"
end
end
end
end

a = Example.new
a.hello('Thomas')
a.hello('Thomas','Edison')

Initializer overloading

The initializer is called when you create a new object.
Method overloading also works for the initializer:

1
2
a = Shape.new(2,4)
b = Shape.new(1,2,3)

To achive that you use an if statement inside the method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Shape
def initialize(*args)
if args.size < 2 || args.size > 3
puts 'Method takes 2 or 3 arguments'
else
if args.size == 2
puts '2 arguments'
else
puts '3 arguments'
end
end
end
end

a = Shape.new(2,4)
b = Shape.new(1,2,3)