Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created January 21, 2020 22:31
Show Gist options
  • Save rodloboz/725dafbb99c44b165a7d52f71fc501e5 to your computer and use it in GitHub Desktop.
Save rodloboz/725dafbb99c44b165a7d52f71fc501e5 to your computer and use it in GitHub Desktop.
Introduction to OOP
# opening a class statement
class Car
# Getter / Reader
# attr_reader :color # => defines a getter
# attr_writer :color # => defines a setter
attr_accessor :color # => defines both
# This is the constructor
# will be called on .new
def initialize(color = "blue")
puts "Creating a car instance..."
# defining an instance variable
@engine_started = false
@color = color
@speed = 0
end
# Getter / Reader
# def color
# @color
# end
# Setter / Writer
# def color=(color)
# @color = color
# end
# Public Interface
def engine_started?
@engine_started
end
def start_engine
start_fuel_pump # call to a private method
spark_plug
@engine_started = true
end
def accelerate
@speed += 50
if @speed < 150
puts "VRUMMMMM..."
puts "The current speed is #{@speed}"
else
puts "You fool! You crashed!"
end
end
def brake
@speed -= 50
puts "Breaking...."
puts "The current speed is #{@speed}"
end
private
def start_fuel_pump
puts "Pumping fuel into the engine..."
end
def spark_plug
puts "Combustion explosion..."
end
end
require 'byebug'
require_relative 'car'
my_car = Car.new
your_car = Car.new
# ask object for internal data
my_car.engine_started?
# user one of the behaviours of the instance
# my_car.start_engine
# my_car.start_fuel_pump
red_ferrari = Car.new("red")
puts "My Ferrari is #{red_ferrari.color}" # => "red"
red_ferrari.color = "orange"
puts "My Ferrari now is #{red_ferrari.color}"
2.times do
red_ferrari.accelerate
end
red_ferrari.brake
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment