Forked from dbc-challenges/P5: OO Inheritance.rb
Last active
December 19, 2015 06:59
-
-
Save michaelchihuyho/5914993 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Vehicle | |
| def initialize(args) | |
| @color = args[:color] | |
| end | |
| def drive | |
| @status = :driving | |
| end | |
| def brake | |
| @status = :stopped | |
| end | |
| def honk | |
| puts "BEEP BEEP" | |
| end | |
| end | |
| class Car < Vehicle | |
| @@WHEELS = 4 | |
| def needs_gas? | |
| return [true,true,false].sample | |
| end | |
| end | |
| class Bus < Vehicle | |
| attr_reader :passengers | |
| def initialize(args) | |
| super | |
| @wheels = args[:wheels] | |
| @num_seats = args[:num_seats] | |
| @fare = args[:fare] | |
| @passengers=[] | |
| end | |
| def drive | |
| return brake if stop_requested? | |
| @status = :driving | |
| end | |
| def admit_passenger(passenger,money) | |
| @passengers << passenger if money > @fare | |
| end | |
| def drop_off_passenger(passenger) | |
| @passengers.delete(passenger) | |
| end | |
| def stop_requested? | |
| return [true,false].sample | |
| end | |
| def needs_gas? | |
| return [true,true,true,false].sample | |
| end | |
| end | |
| class Motorbike < Vehicle | |
| @@WHEELS = 2 | |
| def drive | |
| super | |
| @speed = :fast | |
| end | |
| def needs_gas? | |
| return [true,false,false,false].sample | |
| end | |
| def weave_through_traffic | |
| @status = :driving_like_a_crazy_person | |
| end | |
| end | |
| # Tests | |
| # Should return true unless otherwise specified | |
| car = Car.new({color: "red"}) | |
| p car.drive == :driving | |
| p car.brake == :stopped | |
| p car.needs_gas? # => true 66% of the time | |
| car.honk # => "BEEP BEEP" | |
| bus = Bus.new({color: "white", wheels: 8, num_seats: 18, fare: 2}) | |
| p bus.drive # => :driving or :stopped | |
| p bus.admit_passenger("Bob", 3) == ["Bob"] | |
| bus.admit_passenger("Jane", 1) | |
| p bus.passengers == ["Bob"] | |
| bus.drop_off_passenger("Bob") | |
| p bus.passengers == [] | |
| p bus.brake == :stopped | |
| p bus.stop_requested? # => true 50% of the time | |
| p bus.needs_gas? # => true 75% of the time | |
| bus.honk # => "BEEP BEEP" | |
| motorbike = Motorbike.new({color: "blue"}) | |
| p motorbike.drive == :fast | |
| p motorbike.brake == :stopped | |
| p motorbike.needs_gas? # => true 25% of the time | |
| p motorbike.weave_through_traffic == :driving_like_a_crazy_person | |
| motorbike.honk # => "BEEP BEEP" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment