In a subclass, we can change the behavior of the instances by redefining superclass methods.
class Human
def identify
puts "I'm a person."
end
end
class Student1<Human
def identify
puts "I'm a student."
end
end
Human.new.identify
Student1.new.identify |
Output
I'm a person. I'm a student.
Suppose we would rather enhance the superclass's identify
method than entirely replace it. For this we can use super.
class Human
def identify
puts "I'm a person."
end
end
class Student1<Human
def identify
puts "I'm a student."
end
end
class Student2<Human
def identify
super
puts "I'm a student too."
end
end
print("Human: ")
Human.new.identify
print("Student1: ")
Student1.new.identify
print("Student2: ")
Student2.new.identify |
Output
Human: I'm a person. Student1: I'm a student. Student2: I'm a person. I'm a student too.
super lets us pass arguments to the original method.
It is sometimes said that there are two kinds of people...
class Human
def identify
puts "I'm a person."
end
def train_toll(age)
if age < 12
puts "Reduced fare.";
else
puts "Normal fare.";
end
end
end
class Dishonest<Human
def train_toll(age)
super(11) # we want a cheap fare.
end
end
class Honest<Human
def train_toll(age)
super(age) # pass the argument we were given
end
end
Honest.new.train_toll(25)
Dishonest.new.train_toll(25) |
Output
Normal fare. Reduced fare.


