array = [
["sean", "started", "shift", "at", "10:30:00"],
["anna", "started", "shift", "at", "11:00:00"],
["sean", "started", "shift", "at", "10:41:45"],
["anna", "finished", "shift", "at", "11:30:00"],
["sean", "finished", "shift", "at", "10:48:45"],
["sean", "started", "shift", "at", "11:31:00"],
["sean", "finished", "shift", "at", "11:40:00"]
]
很少有事情需要考虑
如果你看一下肖恩的参赛作品,那么“开始时间”有两个条目'一个在10:30:00,也在10:41:45。系统可以记录多个开始时间'但只有一个'完成'时间。逻辑是首先配对'开始' &安培;第一次完成'并结合它们。
如何跳过重复的“开始时间”'条目(例如Sean' s)并获得所需的输出如下...
array = [
[" sean","开始","转移"," at"," 10:30:00", "完成"," shift"," at"," 10:48:45"],
[" anna","开始"," shift"," at"," 11:00:00", "完成"," shift"," at"," 11:30:00"],
[" sean","开始#34;,"转移"," at"," 11:31:00", "完成"," shift"," at"," 11:40:00"]
]
Theres没有简单的方法吗?
答案 0 :(得分:1)
array.group_by(&:first).map do |person, events|
events.chunk { |_, event_type| event_type }.each_slice(2).map do |(_, (start, _)), (_, (finish, _))|
%W(#{p} started shift at #{start[4]} finished shift at #{finish[4]})
end
end
# => [
# => ["sean", "started", "shift", "at", "10:30:00", "finished", "shift", "at", "10:48:45"],
# => ["sean", "started", "shift", "at", "11:31:00", "finished", "shift", "at", "11:40:00"],
# => ["anna", "started", "shift", "at", "11:00:00", "finished", "shift", "at", "11:30:00"]
# => ]
答案 1 :(得分:0)
started = {}
result = []
array.each do |name, *event|
if event[0] == "started" && !started[name]
result << (started[name] = [name] + event)
elsif event[0] == "finished" && started[name]
started[name].concat(event)
started[name] = nil
end
end
result
编辑完全同意fotanus,BTW。
EDIT2 忘记更改变量名称。另外:逻辑。你依次拿走每一行。 started
将包含已启动但尚未完成的所有记录。所以,连续一下;如果它已经开始&#34;,并且只有当我们不知道那个人已经开始时,请记住开始。如果它已完成&#34;,并且只有当我们已经知道该人已经开始时,才通过附加完成信息来完成记录。