mepython wrote: > I found an error in parse_csv if field is empty, it ignores it for > example: > x,y,z > 1,,2 > > Second line should return [1,nil,2] instead it returns [1,2]. > > How hard to do reverse: create csv string from list? > > Thanks. I just started Ruby couple of days ago, so I am learning > instead of implementing, Sorry. 1,,2 now returns [1, "", 2] Use arry.to_csv to create csv string from array. % ## Record separator. % RS = "\n" % % class String % # Set regexp for parse_csv. % # self is the field-separator, which must be % # a single character. % def is_fs % $csv_fs = self % if "^" == $csv_fs % fs = "\\^" % else % fs = $csv_fs % end % $csv_re = \ % %r! (?: % "( [^"\\]* (?: \\.[^"\\]* )* )" | % ( [^#{fs}]* ) % ) % [#{fs}] % !x % end % def parse_csv % raise "Method #is_fs wasn't called." if $csv_re.nil? % (self+$csv_fs).scan( $csv_re ).flatten.compact % end % end % % class Array % def to_csv % raise "Method #is_fs wasn't called." if $csv_fs.nil? % s = '' % self.each { |x| % x = '"'+x+'"' if x.index( $csv_fs ) or x.index( '"' ) % s += x + $csv_fs % } % s[0 .. -2] % end % end % % % ",".is_fs % % ## Set Ruby's input record-separator. % $/ = RS % % ARGF.each_line { | line | % line.chomp! % puts "-------------------" % puts line % ary = line.parse_csv % p ary % puts ary.to_csv % }