Skip to content

Instantly share code, notes, and snippets.

@worace
Created March 24, 2016 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save worace/1856f064d1315d990e7c to your computer and use it in GitHub Desktop.
Save worace/1856f064d1315d990e7c to your computer and use it in GitHub Desktop.
class Dog # class name is a "constant"
# Objects combine:
# -- state (instance variables)
# -- behavior (methods)
def initialize
# first step in the object's lifecycle
# do i have any setup i actually need to do?
@animals_chased = []
end
# attr_reader :animals_chased (accessor, writer, etc are similar)
# simply defines this method:
def animals_chased
@animals_chased
end
def bark
"woof!" # <-- Bark method will return this value (the string "woof!")
end
# puts -> "side effect"
def chase_animal(animal) # <-- method argument behaves like a local variable
puts "So far, these are the animals I have chased: #{@animals_chased}"
@animals_chased << animal
# do all kinds of stuff up here
#one
# two
# three
"woof! chasing #{animal}"
end
end
fido = Dog.new
spot = Dog.new
fido.bark
class Car
attr_accessor :color
attr_accessor :wheel_count
# allow me to read AND set an instance variable from
# outside of this object
# def color=(new_color)
# @color = new_color
# end
# def color
# @color
# end
def initialize
@started = false # default --> car is NOT started by default
end
def start
if !@started
@started = true
else
"BZZT! Nice try, though."
end
end
def horn
"BEEEP!"
end
def drive(distance)
"I'm driving #{distance} miles"
end
def report_color
# "I am #{@color}" # <-- will look up the ivar directly
"I am #{color}" # <-- will look up the method color which we defined via attr_accessor
end
end
my_car = Car.new
puts my_car.horn
puts my_car.drive(12)
my_car.color = "purple" # <-- thanks to attr_accessor
puts my_car.report_color
my_car.wheel_count = 18
puts "This sweet ride is sitting on #{my_car.wheel_count} wheels"
my_second_car = Car.new
my_second_car.wheel_count = 2
puts "This sweet ride is sitting on #{my_second_car.wheel_count} wheels"
puts my_second_car.start
puts my_second_car.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment