Method: IO#set_encoding_by_bom
- Defined in:
- io.c
#set_encoding_by_bom ⇒ Encoding?
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:
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.
9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 |
# File 'io.c', line 9596 static VALUE rb_io_set_encoding_by_bom(VALUE io) { rb_io_t *fptr; GetOpenFile(io, fptr); if (!(fptr->mode & FMODE_BINMODE)) { rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode"); } if (fptr->encs.enc2) { rb_raise(rb_eArgError, "encoding conversion is set"); } else if (fptr->encs.enc && fptr->encs.enc != rb_ascii8bit_encoding()) { rb_raise(rb_eArgError, "encoding is set to %s already", rb_enc_name(fptr->encs.enc)); } if (!io_set_encoding_by_bom(io)) return Qnil; return rb_enc_from_encoding(fptr->encs.enc); } |