Search code examples
smalltalkpharo

Methods in Pharo


I am still learning Pharo, but it is a bit confusing. There two classes, CarRental and Car, and a Test class, CarRentalTest.

There are fixed number of cars, the same car cannot be rented twice, I have the code, but there is a mistake.

| carRental redPanda yellowPanda blackTesla |
    carRental := CarRental new.
    redPanda := Car panda.
    yellowPanda := Car panda.
    blackTesla := Car tesla.
    carRental
        addCar: redPanda;
        addCar: yellowPanda;
        addCar: blackTesla.
    self assert: carRental availableCars size equals: 3.
    carRental rent: redPanda days: 5.
    self assert: carRental availableCars size equals: 2.
    self assert: carRental rentedCars size equals: 1

I tried to initialize the availableCars and rentedCard methods, but there is still an issue.


Solution

  • You need to keep track of rented cars, right? To do that add the ivar rented to the CarRental class and initialize it to an empty collection:

    rented := OrderedCollection new.
    

    (in other words, include the line above in the #initialize method - instance side.)

    Now, every time you rent a car add it to the rented collection:

    rent: aCar
      rented add: aCar
    

    and when the car is returned

    return: aCar
      rented remove: aCar
    

    Also you can add the getter method which was missing so far

    rentedCars
      ^rented
    

    and compute the cars available for rent as

    availableCars
      ^cars copyWithoutAll: rented