Skip to content

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

instance method

IO#set_encoding_by_bom

set_encoding_by_bom → encoding or nil

If the stream begins with a BOM (byte order marker), consumes the BOM and sets the external encoding accordingly; returns the result encoding if found, or nil otherwise:

Example
File.write('t.tmp', "\u{FEFF}abc")
io = File.open('t.tmp', 'rb')
io.set_encoding_by_bom # => #<Encoding:UTF-8>
io.close

File.write('t.tmp', 'abc')
io = File.open('t.tmp', 'rb')
io.set_encoding_by_bom # => nil
io.close

Raises an exception if the stream is not binmode or its encoding has already been set.

See also #set_encoding #stat #seek #sync also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0