Search code examples
rubycsvfastercsv

Ruby CSV, using square brackets as row separators


I'm trying to use square brackets '[]' as a row separator in a CSV file. I must use this exact format for this project (output needs to match LEDES98 law invoicing format exactly).

I'm trying to do this:

CSV.open('output.txt', 'w', col_sep: '|', row_sep: '[]') do |csv|
     #Do Stuff
end

But Ruby won't take row_sep: '[]' and throws this error:

lib/ruby/1.9.1/csv.rb:2309:in `initialize': empty char-class: /[]\z/ (RegexpError)

I've tried escaping the characters with /'s, using double quotes, etc, but nothing has worked yet. What's the way to do this?


Solution

  • The problem is in CSV#encode_re: the parameter row_sep: "|[]\n" is converted to a Regexp.

    What can redefine this method:

    class CSV
      def encode_re(*chunks)
        encode_str(*chunks)
      end
    end
    CSV.open('output.txt', 'w', col_sep: '|', row_sep: "|[]\n"
      ) do |csv|
       csv << [1,2,3]
       csv << [4,5,6]
    end
    

    The result is:

    1|2|3|[]
    4|5|6|[]
    

    I found no side effect, but I don't feel comfortble to redefine CSV, so I would recommend to create a new CSV-variant:

    #Class to create LEDES98
    class LEDES_CSV < CSV
      def encode_re(*chunks)
        encode_str(*chunks)
      end
    end
    LEDES_CSV.open('output.txt', 'w', col_sep: '|', row_sep: "|[]\n"
      ) do |csv|
       csv << [1,2,3]
       csv << [4,5,6]
    end
    

    Then you can use the 'original' CSV and for LEDES-files you can use the LEDES_CSV.