Parking Garage
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 55 of 57.
Challenge
HardBuild a parking garage. Vehicle stores a plate; its subclasses define size and hourly_rate: Motorbike is size 1 (small) at 1 per hour, Car size 2 (medium) at 3, and Van size 3 (large) at 5. The garage's constant SIZES is %w[small medium large]. Garage.new(small, medium, large) takes the number of spots per size. park(vehicle) puts a vehicle in a free spot of its own size or, if none is free, of the next larger size, and returns parked AB12 in medium or full for AB12. leave(plate, hours) frees the spot and returns AB12 paid 9 (the rate times the hours, at least 1 hour), or no vehicle AB12. status returns free: small 1, medium 0, large 2.
The supplied code reads the spots as small,medium,large, then commands park car AB12, leave AB12 3 or status, and prints each reply.
Your code goes in vehicle.rb, motorbike.rb, car.rb, van.rb and garage.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'vehicle'
require_relative 'motorbike'
require_relative 'car'
require_relative 'van'
require_relative 'garage'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
small, medium, large = input[0].split(",").map(&:to_i)
garage = Garage.new(small, medium, large)
kinds = { "bike" => Motorbike, "car" => Car, "van" => Van }
input.drop(1).each do |cmd|
parts = cmd.split
case parts[0]
when "park" then puts garage.park(kinds[parts[1]].new(parts[2]))
when "leave" then puts garage.leave(parts[1], parts[2].to_i)
else puts garage.status
end
end
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler