Created
May 23, 2013 14:47
-
-
Save enukane/5636607 to your computer and use it in GitHub Desktop.
csv diffing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # task of this script is | |
| # calculate diff | |
| class CSV | |
| def initialize filename | |
| @filename = filename | |
| @f = File.open(@filename) | |
| @data = [] | |
| @diff_map = [] | |
| end | |
| def read_line | |
| @f.gets | |
| end | |
| def parse_line | |
| line = read_line | |
| return nil unless line | |
| ary = line.strip.split(",").map{|str| str.to_i} | |
| return ary | |
| end | |
| def parse | |
| while ary = parse_line | |
| @data << ary | |
| end | |
| end | |
| def array_diff ary0, ary1 | |
| len = ary0.length > ary1.length ? ary0.length : ary1.length | |
| ary = [] | |
| 0.upto(len - 1) do |n| | |
| base0 = ary0[n] || 0 | |
| base1 = ary1[n] || 0 | |
| ary << (base0 - base1) | |
| end | |
| return ary | |
| end | |
| def get_diff | |
| return @diff_map unless @diff_map.empty? | |
| parse | |
| 0.upto (@data.length - 2) do |n| | |
| @diff_map << array_diff(@data[n+1], @data[n]) | |
| end | |
| return @diff_map | |
| end | |
| def print_diff | |
| diffary = get_diff | |
| diffary.each do |ent| | |
| ent.each do |elm| | |
| printf "#{elm}," | |
| end | |
| printf "\n" | |
| STDOUT.flush | |
| end | |
| end | |
| end | |
| csv = CSV.new ARGV.shift | |
| csv.print_diff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment