Ruby Invalid Byte Sequence in UTF-8 Ruby Invalid Byte Sequence in UTF-8 ruby ruby

Ruby Invalid Byte Sequence in UTF-8


The combination of using: @file = IO.read(file).force_encoding("ISO-8859-1").encode("utf-8", replace: nil) and #encoding: UTF-8 solved the issue.


While this question already has an accepted answer, I found it while having the same problem with a different style of opening the file:

File.open(file_name).each_with_index do |line, index|  line.gsub!(/[{}]/, "'")  puts "#{index} #{line}"end

I found that my input file was encoded in ISO-8859-1, so I changed it to the following to avoid the error:

File.open(file_name, 'r:ISO-8859-1:utf-8').each_with_index do |line, index|  line.gsub!(/[{}]/, "'")  puts "#{index} #{line}"end

See the documentation for the optional mode argument of the File.open method for more details.