Advertisement
cd62131

CSV Summation

May 22nd, 2017
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.92 KB | None | 0 0
  1. #!/usr/bin/ruby
  2. require 'csv'
  3. require 'date'
  4. require 'pathname'
  5.  
  6. CSV::Converters.update({ force_date: lambda {|f| Date.strptime(f, '%Y/%m/%d') rescue f } })
  7.  
  8. in_dir = '/home/data'
  9. out_dir = '/home/ranking'
  10. today = Date.today
  11.  
  12. CSV.open(
  13.   Pathname(out_dir).join((today - 1).strftime('%Y%m%d') + '.csv'), 'w',
  14.   :headers => %w(RANKING USER TOTAL), :write_headers => true
  15. ) {|csv|
  16.   Pathname(in_dir).children.select {|e| e.fnmatch('*.csv', File::FNM_CASEFOLD) }
  17.   .map {|e|
  18.     {
  19.       user: e.basename(e.extname).to_s,
  20.       total: CSV.read(
  21.                e,
  22.                :converters => [:force_date, :integer],
  23.                :headers => :first_row,
  24.                :return_headers => false
  25.              ).select {|a| today - a['DATE'] == 1 }
  26.              .inject(0) {|s, a| s += a['DATA1'] + a['DATA2'] }
  27.     }
  28.   }.sort_by {|e| -e[:total] }
  29.   .each_with_index {|e, i| csv << [i + 1, e[:user], e[:total]] }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement