Skip to content

Instantly share code, notes, and snippets.

@nscricco
Forked from dbc-challenges/P5: OO Inheritance.rb
Last active December 22, 2015 13:19
Show Gist options
  • Save nscricco/6478720 to your computer and use it in GitHub Desktop.
Save nscricco/6478720 to your computer and use it in GitHub Desktop.
class Vehicle
@@WHEELS = 4
attr_reader :speeding_tickets
def initialize(args)
@color = args[:color]
@speeding_tickets = 0
end
def drive
@status = :driving
end
def brake
@status = :stopped
end
def caught_speeding
@speeding_tickets += 1 if @status == :driving_like_a_crazy_person
end
end
class Car < Vehicle
def initialize(args)
super
@wheels = @@WHEELS
@sunroof = :open
end
def needs_gas?
return [true,true,false].sample
end
def close_sunroof
@sunroof = :closed
end
def open_sunroof
@sunroof = :open
end
end
class Bus < Vehicle
attr_reader :passengers
def initialize(args)
super
@wheels = args[:wheels] || @@WHEELS
@num_seats = args[:num_seats]
@fare = args[:fare]
@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?
return [true,true,true,false].sample
end
end
class Motorbike < Vehicle
@@WHEELS = 2
def initialize(args)
super
@wheels = @@WHEELS
end
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
#Car
puts 'Car test'
first_car = Car.new({:color => 'blue'})
puts "Drive: #{first_car.drive}"
puts "Brake: #{first_car.brake}"
puts "Needs gas? #{first_car.needs_gas?}"
puts "Open sunroof: #{first_car.open_sunroof}"
puts "Close sunroof: #{first_car.close_sunroof}"
puts "Po-po drives by"
first_car.caught_speeding
puts "Car has #{first_car.speeding_tickets} tickets"
puts
#Bus
puts 'Bus test'
first_bus = Bus.new({:color => 'yellow', :num_seats => 10, :fare => 2})
first_bus.admit_passenger('Nick', 3)
first_bus.admit_passenger('Danielle', 1)
first_bus.admit_passenger('Tyler', 5)
puts "Passengers: #{first_bus.passengers == ['Nick','Tyler']}"
puts "Drive: #{first_bus.drive} "
puts "Drive: #{first_bus.drive}"
puts
#Motorbike
puts 'Motorbike test'
first_motorbike = Motorbike.new({:color => 'Red'})
puts "Drive: #{first_motorbike.drive}"
puts "Brake: #{first_motorbike.brake}"
puts "Needs gas? #{first_motorbike.needs_gas?}"
puts "Weaving? #{first_motorbike.weave_through_traffic}"
puts "Po-po drives by"
first_motorbike.caught_speeding
puts "Car has #{first_motorbike.speeding_tickets} tickets"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment