Skip to content

Instantly share code, notes, and snippets.

@844196
Last active January 25, 2016 19:49
Show Gist options
  • Select an option

  • Save 844196/d7e7d06f3be0d876f7d7 to your computer and use it in GitHub Desktop.

Select an option

Save 844196/d7e7d06f3be0d876f7d7 to your computer and use it in GitHub Desktop.
配列を渡すと、先頭からブロック内の条件に一致する要素を返し、同時に配列から取り除くメソッド
エージェント ログオンユーザー 日付 イベント時刻
PC_A UserA 2000/01/01 00:00:00
PC_A UserA 2000/01/01 01:00:00
PC_A UserA 2000/01/01 02:00:00
PC_C UserA 2000/01/01 02:30:00
PC_C UserA 2000/01/01 03:00:00
PC_A UserB 2000/01/01 04:00:00
PC_C UserA 2000/01/01 04:30:00
PC_A UserB 2000/01/01 05:00:00
PC_A UserB 2000/01/01 06:00:00
エージェント ログオンユーザー 日付 イベント時刻 終了時刻
PC_A UserA 2000/01/01 00:00:00 02:00:00
PC_C UserA 2000/01/01 02:30:00 04:30:00
PC_A UserB 2000/01/01 04:00:00 06:00:00
require 'csv'
require 'pp'
array_of_rows = CSV.parse(DATA, :headers => true).map {|row| row }
def shift_by(array, &block)
i = array.each_with_index.each_with_object(nil) do |(item, index), n|
break index unless block.call(item)
end
i ? array.shift(i) : array.slice!(0..-1)
end
array_of_rows
.map! {|row| row['session'] = "#{row['エージェント']}_#{row['ログオンユーザー']}"; row }
.sort_by! {|row| [row['エージェント'], row['日付'], row['イベント時刻']] }
out = []
until array_of_rows.size.zero?
out << shift_by(array_of_rows) {|row| row['session'] == array_of_rows.first['session'] }
end
table = out.map do |ary|
ary.first['終了時刻'] = ary.last['イベント時刻'];
ary.first.delete('session')
ary.first
end
table.sort_by! {|row| [row['日付'], row['イベント時刻'], row['終了時刻']] }
puts CSV::Table.new(table).to_csv
__END__
エージェント,ログオンユーザー,日付,イベント時刻
PC_A,UserA,2000/01/01,00:00:00
PC_A,UserA,2000/01/01,01:00:00
PC_A,UserA,2000/01/01,02:00:00
PC_C,UserA,2000/01/01,02:30:00
PC_C,UserA,2000/01/01,03:00:00
PC_A,UserB,2000/01/01,04:00:00
PC_C,UserA,2000/01/01,04:30:00
PC_A,UserB,2000/01/01,05:00:00
PC_A,UserB,2000/01/01,06:00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment