Write and read a file with utf-8 encoding Write and read a file with utf-8 encoding ruby ruby

Write and read a file with utf-8 encoding


If i execute your code i get an error on the special character. Can you try this code ?

# encoding: UTF-8File.open("test.txt", "w:UTF-8") do |f|   f.write "test \u00A9 foo" end #Encoding.filesystem = "UTF-8"p Encoding.find("filesystem") File.open("test.txt", "r:UTF-8") do |f|   puts f.read end 

On my windows box i then get

#<Encoding:Windows-1252>test © foo

I have no idea why the  is there..


Read the file with less code:

# encoding: UTF-8file_content = File.open("test.txt", "r:UTF-8", &:read)


On which OS does your application run? It could be that the default encoding for the file is ASCII. Does it help if you add w:utf-8 and r:utf-8 to the open parameters?