Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created August 5, 2020 08:08
Show Gist options
  • Save rodloboz/c02074d65c3419d3b06f7b7a6c065a19 to your computer and use it in GitHub Desktop.
Save rodloboz/c02074d65c3419d3b06f7b7a6c065a19 to your computer and use it in GitHub Desktop.
Car Class
# color, brand, speed
# Class names are in UpperCamelCase
# Open a class statement
class Car
attr_reader :brand, :license_plate # Creates GETTERS
# attr_writer :color # Creates SETTERS
attr_accessor :color # Creates GETTERS and SETTERS
# This is the constructor
# it will be called in Car.new
def initialize(brand, color = "blue")
# Define instance variables (DATA/STATE):
@brand = brand
@color = color
@speed = 0
@engine_started = false
@license_plate = create_registration
puts "Created a car instance 🚗 with license plate number #{@license_plate}"
end
# Getter / Reads internal data
# def color
# @color
# end
# Setter / Writes internal data
# def color=(color)
# @color = color
# end
# PUBLIC INTERFACE (BEHAVIOR)
def engine_started?
@engine_started
end
def start_engine
start_fuel_pump
fire_spark_plug
@engine_started = true
end
def accelerate
return unless engine_started?
@speed += 50
if @speed <= 150
puts "VRUMMMMM.... #{'🏎' * (@speed / 50)}"
else
@engine_started = false
puts "You fool! You crashed! 🚑"
end
end
def brake
return if @speed.zero?
@speed -= 50
puts "Braking..."
end
private
def create_registration
digits = (0..9).to_a.sample(4).join
letters = ("A".."Z").to_a.sample(3).join
# [digits, letters].join("-")
"#{digits}-#{letters}"
end
def start_fuel_pump
puts "Pumping fuel into the engine... ⛽️⛽️⛽️"
end
def fire_spark_plug
puts "Combustion explosion 💥"
end
end
require_relative "car"
require "byebug"
puts "==================CARS=================="
my_car = Car.new("Honda")
your_car = Car.new("Seat", "green")
puts "My car is a #{my_car.color} #{my_car.brand}"
puts "Your car is a #{your_car.color} #{your_car.brand}"
puts "Let's paint my car!"
my_car.color = "red"
puts "Now, my car is #{my_car.color}"
your_car.start_engine # public interface
# It's not possible to call private methods
# your_car.start_fuel_pump
if your_car.engine_started?
puts "Your car is running..."
else
puts "Your car is parked"
end
puts "==================FERRARI=================="
ferrari = Car.new("Ferrari", "red")
ferrari.start_engine
ferrari.accelerate
ferrari.brake
6.times { ferrari.accelerate }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment