kahonmlg
kahonmlg

Reputation: 4049

CSV writing Ruby Encoding Error

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

Upvotes: 0

Views: 1171

Answers (1)

dawg
dawg

Reputation: 104092

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.

Upvotes: 1

Related Questions