Method overriding is a language feature. Its part of the object-oriented programming concept.

If you have two classes, the implementation of a sub class replaces (overrides) the implementation of the super class.

Simplified, you can call it “method replacement”.

Download Free Ruby Ebook

Method overriding in ruby

Overriding example

The ruby program below creates defines two classes with the same method. Class SUB inherits from the SUPER class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/ruby

class SUPER
def hello
puts 'In class SUPER'
end
end

class SUB < SUPER
def hello
puts 'In class SUB'
end
end

b = SUB.new()
b.hello()

Class SUB replaces the implementation of the method hello. Once a new object is created, that implementation is used.

If the method is not defined in the sub class, it will use the implementation of the super class.

Redefining methods

Methods can be redefined. It will always use the latest method. It’s recommended that you only use one method definition.

1
2
3
4
5
6
7
8
9
10
11
class EXAMPLE
def hello
puts 'In class Example'
end
def hello
puts 'hello'
end
end

b = EXAMPLE.new()
b.hello()