假设我们有以下时间表。
schedule =<<~END
Blocks,15:00,15:10,15:55
Teacher 1,Stu A,Stu B,Stu C
Teacher 2,Stu B,Stu C,Stu A
Teacher 3,Stu C,Stu A,Stu B
END
要生成所需的哈希数组,我们需要额外的信息。假设我们也得到以下内容。
teacher_emails = {
"Teacher 1"=>"teacher.1@school.edu",
"Teacher 2"=>"teacher.2@school.edu",
"Teacher 3"=>"teacher.3@school.edu"
}
parent_emails = {
"Stu A"=> { "Parent 1"=>"stuap1@example.com",
"Parent 2"=>"stuap2@example.com" },
"Stu B"=> { "Parent"=>"stubp@example.com" },
"Stu C"=> { "Parent 1"=>"stuapc@example.com",
"Parent 2"=>"stuapc@example.com" }
}
mins_per_meeting = 8
那么我们可以进行如下操作。
blks, *sched = schedule.split(/\n/)
blks
#=> "Blocks,15:00,15:10,15:55"
sched
#=> ["Teacher 1,Stu A,Stu B,Stu C",
# "Teacher 2,Stu B,Stu C,Stu A",
# "Teacher 3,Stu C,Stu A,Stu B"]
time_blocks = blks.scan(/\d{1,2}:\D{2}/).map do |s|
hr, min = s.split(':')
mins_from_midnight = 60*(hr.to_i) + min.to_i
{ start: "%d:%02d" % mins_from_midnight.divmod(60),
{ end: "%d:%02d" % (mins_from_midnight + mins_per_meeting).divmod(60),
end
#=> [{:start=>"15:00", :end=>"15:08"},
# {:start=>"15:10", :end=>"15:18"},
# {:start=>"15:55", :end=>"16:03"},
sched.map do |s|
teacher, *students = s.split(',')
{ name: teacher,
email: teacher_emails[teacher],
appointments: time_blocks.zip(students).map do |tb,stud|
tb.merge(
{ student: stud,
attendees: parent_emails[stud].map do |par_name, par_email|
{ name: par_name, email: par_email }
end
}
)
end
}
end
#=> [{:name=>"Teacher 1", :email=>"teacher.1@school.edu",
# :appointments=>[
# {:start=>"15:00", :end=>"15:08",
# :student=>"Stu A",
# :attendees=>[
# {:name=>"Parent 1", :email=>"stuap1@example.com"},
# {:name=>"Parent 2", :email=>"stuap2@example.com"}
# ]
# },
# {:start=>"15:10", :end=>"15:18",
# :student=>"Stu B",
# :attendees=>[
# {:name=>"Parent", :email=>"stubp@example.com"}
# ]
# },
# {:start=>"15:55", :end=>"16:03",
# :student=>"Stu C",
# :attendees=>[
# {:name=>"Parent 1", :email=>"stuapc@example.com"},
# {:name=>"Parent 2", :email=>"stuapc@example.com"}
# ]
# }
# ]
# },
# {:name=>"Teacher 2", :email=>"teacher.2@school.edu",
# :appointments=>[
# {:start=>"15:00", :end=>"15:08",
# :student=>"Stu B",
# :attendees=>[
# {:name=>"Parent", :email=>"stubp@example.com"}
# ]
# },
# ....