Skip to content

Instantly share code, notes, and snippets.

@creature
Created January 14, 2014 15:10
Show Gist options
  • Select an option

  • Save creature/8419806 to your computer and use it in GitHub Desktop.

Select an option

Save creature/8419806 to your computer and use it in GitHub Desktop.
A simple example of object orientation
class Hotel
DOUBLE_ROOM_CAPACITY = 2
SINGLE_ROOM_CAPACITY = 1
def initialize(double_count, single_count)
@rooms = []
@capacity = 0
@guestbook = []
double_count.times do
@rooms << Room.new(DOUBLE_ROOM_CAPACITY)
@capacity += DOUBLE_ROOM_CAPACITY
end
single_count.times do
@rooms << Room.new(SINGLE_ROOM_CAPACITY)
@capacity += SINGLE_ROOM_CAPACITY
end
end
def report
vacancy_count = 0
@rooms.each {|r| vacancy_count += r.capacity unless r.occupied? }
puts "#{@rooms.count} rooms with space for #{@capacity} people (#{vacancy_count} vacancies)."
@guestbook.each {|g| puts "#{g} stayed in our hotel."}
end
def add_guest(guest)
puts "Checking in #{guest}..."
available_rooms = @rooms.select {|r| r.single? and not r.occupied? }
if available_rooms.length > 0
room = available_rooms.first
else
room = @rooms.select {|r| not r.occupied? }
end
room.add(guest)
@guestbook << guest.name
end
end
class Room
attr_reader :capacity
def initialize(capacity)
@capacity = capacity
@people = []
end
def occupied?
@people.any?
end
def single?
@capacity == 1
end
def add(guest)
@people << guest
end
end
class Visitor
attr_reader :name
def initialize(name)
@name = name
end
def to_s
@name
end
end
bates_motel = Hotel.new(3, 5)
bates_motel.report
puts "-------"
tim = Visitor.new("Tim")
max = Visitor.new("Max P")
clem = Visitor.new("Clem")
bates_motel.add_guest tim
bates_motel.report
puts "-------"
bates_motel.add_guest max
bates_motel.report
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment