0
votes

I am trying to write a UTF-8 character in a CSV file with csv library of Ruby. And I have got an error:

csv ruby write problem ASCII-8BIT (Encoding::CompatibilityError)

#create csv file
CSV.open(CSV_file,"wb",) do |csv|
  csv << First_line
  rows.each do  |r|
    csv << r.generate_array
  end
end

That's the code where UTF-8 conflicts with ASCII-8BIT.

Example text that fails:

demás

1
ruby 2.3.4p301 (2017-03-30 revision 58214) [x86_64-linux-gnu] Ubuntu 16.04 uname -r 4.10.0-28-generic - kahonmlg
I want to write UTF-8 into a the file. - kahonmlg
r is a class called CSV_row that I have create. They are objects generated in the same script. Taking data from others files, and generating a object with text information that will be inserted to the CSV. - kahonmlg
If you write utf-8, why not use CSV.open(CSV_file,"w:utf-8"? YOur example can't be used to show details. E.g. what is rows in your code? - knut
Please add example text - dawg

1 Answers

1
votes

Here is an example of CSV writing and reading with UTF-8:

fn="/tmp/f.csv"

require "csv"
d1=DATA.read.split(/\n/).map {|e| e.split}
CSV.open(fn, "w:utf-8") do |row|
   d1.each { |dr| row << dr }
end

d2=[]
CSV.foreach(fn) do |row|
  d2 << row
end

puts d1==d2
# true

__END__
privé face à face à un tête-à-tête
Face to face with one-on-one
demás

Without a more detailed example from you, I cannot help further.