Skip to content

Instantly share code, notes, and snippets.

@droberts-sea
Created September 8, 2017 16:50
Show Gist options
  • Save droberts-sea/286473778dcba3147a0fbebb39ab1e96 to your computer and use it in GitHub Desktop.
Save droberts-sea/286473778dcba3147a0fbebb39ab1e96 to your computer and use it in GitHub Desktop.
# An Instructor represents a single instructor
class Instructor
attr_reader :donut_count
def initialize
@donut_count = 0
end
def eat_donut
@donut_count += 1
end
end
# An InstructorTeam represents a collection of instructors
class InstructorTeam
attr_reader :instructors
def initialize
@instructors = []
end
def add
@instructors << Instructor.new
end
def bring_in_donuts
@instructors.each do |instructor|
rand(3).times do
instructor.eat_donut
end
end
end
end
liberal_arts_dept = InstructorTeam.new
6.times do |i|
liberal_arts_dept.add
end
puts "#{liberal_arts_dept.instructors.length} liberal arts teachers"
# => 6 liberal arts teachers
science_dept = InstructorTeam.new
10.times do
science_dept.add
end
puts "#{science_dept.instructors.length} science teachers"
# => 10 science teachers
# An alternate (and arguably less good) way of organizing
# things is to store the collection in a class variable
class Student
@@all_students = []
def initialize
# Whenever a new instance is created, it is
# automatically added to the collection
# Note the use of self to reference the current object
@@all_students << self
end
# Need an accessor method here because attr_reader
# doesn't work for class variables
def self.all_students
return @@all_students
end
end
24.times do
Student.new
end
puts "#{Student.all_students.length} students"
# => 24 students
# The reason this technique is not recommended is because we're
# limited to one collection of students. If we wanted to split
# students out into cohorts, we'd have to do a bunch of redesign.
# In essence, the Student class is responsible for two things:
# keeping track of a single student and keeping track of the
# set of all students. Better to separate this out into two classes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment