Skip to content

CSV Diff — Ruby source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# csv-diff — key-based row diff of two RFC-4180 CSVs. Ruby port (canonical TS:
# src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the JS/Python ports:
# RFC-4180 parse (quoted cells with embedded commas, quotes, newlines; CR
# dropped; no-newline flush) with blank single-cell rows dropped as trailing
# noise, strict per-side validation (empty CSV, duplicate columns, ragged
# rows, duplicate keys — reported as error strings, never exceptions), then a
# key-based diff over the sorted key union: added/removed rows and changed
# rows whose differing column names come out sorted.
module CsvDiff
  module_function

  # RFC 4180 parser mirroring the TS loop: lenient quotes, CR dropped, a
  # trailing field without a newline still completes its row.
  def csv_to_rows(csv)
    rows = []
    field = +''
    row = []
    in_q = false
    i = 0
    n = csv.length
    while i < n
      ch = csv[i]
      if in_q
        if ch == '"'
          if i + 1 < n && csv[i + 1] == '"'
            field << '"'
            i += 1
          else
            in_q = false
          end
        else
          field << ch
        end
      elsif ch == '"'
        in_q = true
      elsif ch == ','
        row << field
        field = +''
      elsif ch == "\n"
        row << field
        rows << row
        row = []
        field = +''
      elsif ch != "\r"
        field << ch
      end
      i += 1
    end
    if !field.empty? || !row.empty?
      row << field
      rows << row
    end
    rows
  end

  # Blank single-cell rows are trailing noise to a diff, not data.
  def parse_csv(text)
    csv_to_rows(text).reject { |r| r.length == 1 && r[0].empty? }
  end

  # Strict per-side validation; raises RuntimeError with the pinned strings.
  def to_records(rows, label)
    raise "#{label}: empty CSV" if rows.empty?
    header = rows[0]
    seen = []
    header.each do |name|
      raise "#{label}: duplicate column \"#{name}\"" if seen.include?(name)
      seen << name
    end
    records = []
    rows[1..].each_with_index do |r, i|
      raise "#{label}: row #{i + 2} has #{r.length} cells, expected #{header.length}" if r.length != header.length
      records << header.zip(r).to_h
    end
    [header, records]
  end

  # Diff two CSVs by key column (default: the first header column).
  def csv_diff(left_raw, right_raw, key_column = nil)
    return { rows: [], same: false, error: 'Both inputs are required' } if left_raw.strip.empty? || right_raw.strip.empty?
    begin
      lheader, lrecs = to_records(parse_csv(left_raw), 'Left')
      rheader, rrecs = to_records(parse_csv(right_raw), 'Right')
      key = key_column || lheader[0]
      return { rows: [], same: false, error: "Left: no key column \"#{key}\"" } unless lheader.include?(key)
      return { rows: [], same: false, error: "Right: no key column \"#{key}\"" } unless rheader.include?(key)
      return { rows: [], same: false,
               error: "Headers differ: left [#{lheader.join(', ')}] vs right [#{rheader.join(', ')}]" } if lheader != rheader

      index = lambda do |records, label|
        by = {}
        records.each do |rec|
          raise "#{label}: duplicate key \"#{rec[key]}\"" if by.key?(rec[key])
          by[rec[key]] = rec
        end
        by
      end
      left_by = index.call(lrecs, 'Left')
      right_by = index.call(rrecs, 'Right')
      out = []
      (left_by.keys | right_by.keys).sort.each do |k|
        l = left_by[k]
        r = right_by[k]
        if l.nil?
          out << { key: k, type: 'added', after: r }
        elsif r.nil?
          out << { key: k, type: 'removed', before: l }
        else
          columns = lheader.select { |n| n != key && l[n] != r[n] }.sort
          out << { key: k, type: 'changed', columns: columns, before: l, after: r } unless columns.empty?
        end
      end
      { rows: out, same: out.empty?, error: nil }
    rescue RuntimeError => e
      { rows: [], same: false, error: e.message }
    end
  end
end

# Example:
# CsvDiff.csv_diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New")[:rows]
# → [{key: "2", type: "changed", columns: ["name"], before: {…}, after: {…}},
#    {key: "3", type: "added", after: {"id" => "3", "name" => "New"}}]

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →