Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

IO#set_encoding_by_bom

ios.set_encoding_by_bom → encoding or nil

Checks if ios starts with a BOM, and then consumes it and sets the external encoding. Returns the result encoding if found, or nil. If ios is not binmode or its encoding has been set already, an exception will be raised.

Example
File.write("bom.txt", "\u{FEFF}abc")
ios = File.open("bom.txt", "rb")
ios.set_encoding_by_bom    #=>  #<Encoding:UTF-8>

File.write("nobom.txt", "abc")
ios = File.open("nobom.txt", "rb")
ios.set_encoding_by_bom    #=>  nil
See also #set_encoding #stat #seek #sync also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0