Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.
class Schedule
attr_accessor :entries
def initialize
@entries = []
end
def add_entry(teacher, class_name, semester)
if entry_exists?(teacher, class_name, semester)
puts "Entry already exists for this teacher, class, and semester combination."
else
@entries << { teacher: teacher, class_name: class_name, semester: semester }
puts "Entry added successfully."
end
end
private
def entry_exists?(teacher, class_name, semester)
@entries.any? { |entry| entry[:teacher] == teacher && entry[:class_name] == class_name && entry[:semester] == semester }
end
end
# Example usage:
schedule = Schedule.new
schedule.add_entry("John Doe", "Math 101", "Fall 2023")
schedule.add_entry("Jane Smith", "Math 101", "Fall 2023") # This entry will be rejected
schedule.add_entry("John Doe", "Math 101", "Fall 2023") # This entry will be rejected
schedule.add_entry("John Doe", "Physics 201", "Fall 2023") # This entry will be accepted
In this Ruby code, a Schedule
class is defined to manage teacher entries on the schedule. The add_entry
method is used to add a new entry to the schedule, checking if an entry already exists for the given teacher, class, and semester combination using the private method entry_exists?
. If an entry already exists, a message is displayed, and the entry is not added. Otherwise, the new entry is added to the schedule. The example usage demonstrates how to use the Schedule
class to add entries to the schedule, with appropriate messages for successful and unsuccessful additions.