Skip to content

Instantly share code, notes, and snippets.

@aloewright
Forked from dbc-challenges/P5: OO Inheritance.rb
Last active December 20, 2015 05:18
Show Gist options
  • Select an option

  • Save aloewright/6076848 to your computer and use it in GitHub Desktop.

Select an option

Save aloewright/6076848 to your computer and use it in GitHub Desktop.
=begin
I made three classes (types) of vehicles that inherit the behavior of one super class
called Vehicle. I arranged it following OO Design, using single responsibility methods.
=end
class Vehicle
attr_reader :passengers, :wheels, :num_seats, :fare, :color
def initialize(args)
@color = args[:color]
end
def drive
@status = :driving
end
def brake
@status = :stopped
end
def needs_gas?(probability)
return probability.sample
end
end
class Car < Vehicle
def initialize(args)
@wheels = 4
end
def needs_gas?
super([true,true,false])
end
end
class Bus < Vehicle
def initialize(args)
@wheels = args[:wheels]
@num_seats = args[:num_seats]
@fare = args[:fare]
@passengers = args[:passengers]
end
def drive
return self.brake if stop_requested?
super
end
def admit_passenger(passenger, money)
@passengers << passenger if money >= @fare
end
def stop_requested?
return [true,false].sample
end
def needs_gas?
super([true,true,true,false])
end
end
class Motorbike < Vehicle
def initialize(args)
@wheels = 2
end
def drive
@status, @speed = :driving, :fast
end
def needs_gas?
super([true,false,false,false])
end
def weave_through_traffic
@status = :driving_like_a_crazy_person
end
end
car_params = {
color: "Silver",
wheels: "8",
num_seats: "5",
passengers: "Sally",
fare: 2,
}
mini_cooper = Car.new(car_params)
p mini_cooper.drive == :driving
p mini_cooper.brake == :stopped
p [true, false].include?(mini_cooper.needs_gas?)
suzuki = Motorbike.new(car_params)
p suzuki.drive == [:driving, :fast]
p [true, false].include?(suzuki.needs_gas?)
p suzuki.weave_through_traffic == :driving_like_a_crazy_person
public_transit = Bus.new(car_params)
p [:driving, :stopped].include?(public_transit.drive)
p public_transit.admit_passenger("Johnny", 2) == "SallyJohnny"
p [true, false].include?(public_transit.stop_requested?)
p [true, false].include?(public_transit.needs_gas?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment