Ruby: How to load a file with a known encoding

In case Ruby does not detected the expected encoding of a file automatically you can specify the known encoding manually.

Example with File.open

file = File.open('some.bin', encoding: Encoding::ASCII_8BIT)
text = file.read
text.encoding => #<Encoding:ASCII-8BIT>

Example with File.read

text = File.read('some.bin', encoding: Encoding::ASCII_8BIT)
text.encoding => #<Encoding:ASCII-8BIT>

More details about the encoding of strings in Ruby can be found here.

Emanuel Over 3 years ago