Chapitre IV : Programmation objet
1. Étape 1 : La classe Vehicule
class Vehicule
attr_reader :enFonctionnement
def initialize( model )
@model = model
end
def demarrer()
@enFonctionnement = true
end
def arreter()
@enFonctionnement = false
end
end
moto = Vehicule.new( "Moto" )
moto.demarrer
puts moto.inspect
moto.arreter
puts moto.inspect
if moto.enFonctionnement then
puts "Il y a une erreur de fonctionnement"
else
puts "Tout fonctionne correctement"
end
Nous obtenons en sortie :
#<Vehicule:0x2b68878 @enFonctionnement=true, @model="Moto">
#<Vehicule:0x2b68878 @enFonctionnement=false, @model="Moto">
Tout fonctionne correctement
2. Étape 2 : La classe Moteur
class Moteur
attr_reader :carburant
def initialize()
@carburant = 0
end
def demarrer()
if ( @carburant > 0 ) then
@carburant = @carburant - 1
puts "Démarrage avec #{carburant}"
true
else
puts "Impossible de démarrer"
false
end
end
def utiliser( consommation )
if ( @carburant > consommation ) then
@carburant = @carburant - consommation
puts "Usage avec #{carburant}"
else
puts "C'est la panne !"
@carburant = 0
end
end
def arreter()
puts "Arrêt du moteur"
end
def fairePlein( qte )
@carburant = @carburant + qte
puts "Prêt à fonctionner avec #{carburant}"
end
end
m = Moteur.new
m.demarrer
m.fairePlein( 50 )
m.demarrer
m.utiliser( 30 )
m.utiliser( 30 )
m.arreter
Nous obtenons en sortie :
Impossible de démarrer
Prêt...