Ruby Inheritance

It’s ideal to keep your code DRY ( Don’t repeat yourself) rather then WET (Writing everything twice). Keeping things “dry” reduces the repetition of your information and code within your app making it easier to manage. Inheritance is one way to do so. Inheritance groups a method into a parent class that may be commonly used by other individual classes . In the example below there is a car class and bike class that have similar methods, A transportation class is created so that the code for the car class and bike class can be “dry”. Both the car and bike classes inherit from that transportation class giving them the same methods they had previously without having to write that code twice and also allows you to use the transportation class for future classes like a bus or train.

Class Car

class Car

def initialize
@speed = 0
@direction = 'north'
end
 def brake    
@speed = 0
end
 def accelerate    
@speed += 10
end

def turn(new_direction)
@direction = new_direction
end

def honk_horn
puts "Beeeeeeep!"
end
end

Class Bike

class Bike  
 def initialize    
@speed = 0
@direction = 'north'
end

def brake
@speed = 0
end
 def accelerate    
@speed += 10
end
 def turn(new_direction)    
@direction = new_direction
end
 def ring_bell    
puts "Ring ring!"
end
end

Class Transportation

class Transportation   
 def initialize    
@speed = 0
@direction = 'north'
end
 def brake    
@speed = 0
end
 def accelerate    
@speed += 10
end
 def turn(new_direction)    
@direction = new_direction
end
end

Inheritance for Classes Car and Bike

class Car < Transportation    
 def honk_horn    
puts "Beeeeeeep!"
end
end

class Bike < Transportation  
def ring_bell
puts "Ring ring!"
end
end