Ruby is an object-oriented programming language. This example demonstrates a superclass for representing a car. Two subclasses are used for representing a hero car and a villain car, they inherit from the superclass.
#!/usr/bin/env ruby
class Car
# Define getters and setters
attr_accessor :model, :maxSpeed, :fuel
# Constructor
def initialize(model, maxSpeed, fuel)
@model = model
@maxSpeed = maxSpeed
@fuel = fuel
end
def drive
puts 'Driving..'
end
# Instance to string
def to_s
'Model: ' + @model + "\n" +
'Maximum speed: ' + @maxSpeed + "\n" +
'Fuel: ' + @fuel
end
end
# Inheritance
class VillainCar < Car
def drive
puts 'Boo!'
end
end
class HeroCar < Car
def drive
puts 'Woo!'
end
end
carBatman = HeroCar.new("Batmobile","531 km/h","High octane")
carJoker = VillainCar.new("Jokermobile","100 km/h","Helium");
# Display both cars
puts 'Batman drives: '
puts carBatman.to_s + "\n\n"
puts 'The Joker drives: '
puts carJoker.to_s + "\n\n"
# Drive both cars
carBatman.drive
carJoker.drive
Output:
Batman drives: Model: Batmobile Maximum speed: 531 km/h Fuel: High octane The Joker drives: Model: Jokermobile Maximum speed: 100 km/h Fuel: Helium Woo! Boo!