Skip to content

Instantly share code, notes, and snippets.

@ericchen0121
Forked from dbc-challenges/P5: OO Inheritance.rb
Last active December 19, 2015 14:39
Show Gist options
  • Save ericchen0121/5970654 to your computer and use it in GitHub Desktop.
Save ericchen0121/5970654 to your computer and use it in GitHub Desktop.
class Vehicle
attr_reader :status, :color, :wheels
def initialize(args)
@color = args[:color]
end
def drive
@status = :driving
end
def brake
@status = :stopped
end
def needs_gas?(randomness = [true, false])
return randomness.sample
end
end
class Car < Vehicle
@@WHEELS = 4
def initialize(args)
super
@wheels = @@WHEELS
end
def needs_gas?
super([true, true, false])
end
end
class Bus < Vehicle
attr_reader :passengers, :fare, :num_seats, :wheels
def initialize(args)
super
@wheels = args[: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?
super([true,true,true,false])
end
end
class Motorbike < Vehicle
attr_reader :speed
@@WHEELS = 2
def initialize(args)
super
@wheels = @@WHEELS
end
def drive
super
@speed = :fast
end
def needs_gas?
super([true,false,false,false])
end
def weave_through_traffic
@status = :driving_like_a_crazy_person
end
end
# Car Class Driver code
puts 'The Lexus is rolling off the manufacturing line.'
lexus = Car.new({color: 'red'})
lexus.drive
p lexus.status == :driving
lexus.brake
p lexus.status == :stopped
p "Does the car need gas? #{lexus.needs_gas?}"
# Bus Class Driver Code
puts ""
puts 'The greyhound bus is being created: '
greyhound = Bus.new({color: 'grey', wheels: 8, num_seats: 50, fare: 2})
# Both these work: initializing with argument parameters and with a hash
# Why do both of them work the same?
# greyhound = Bus.new(color: 'grey', wheels: 8, num_seats: 50, fare: 2 )
p greyhound.fare.class == Fixnum
greyhound.admit_passenger('Eric', 20)
p greyhound.passengers[0] == 'Eric'
bus_status = greyhound.drive
puts (bus_status == :driving || bus_status == :stopped)
p greyhound.brake == :stopped
p greyhound.stop_requested? != nil
p greyhound.needs_gas? != nil
# Motorbike Driver Code
puts ""
puts 'The Ducati is careening down the highway.'
ducati = Motorbike.new({color: 'blue'})
ducati.drive
p "The Ducati is speeding through the red light district, it's #{ducati.status} and it is going really #{ducati.speed}!"
p "The Ducati hit a red light. It is now #{ducati.brake}."
p "The Ducati has been driving for awhile. Does it need gas? #{ducati.needs_gas?}."
p "The Ducati is being chased by police! He's now #{(ducati.weave_through_traffic).to_s.gsub('_', ' ')}!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment