Method: String#encode
- Defined in:
- transcode.c
#encode(encoding, **options) ⇒ String #encode(dst_encoding, src_encoding, **options) ⇒ String #encode(**options) ⇒ String
The first form returns a copy of str
transcoded to encoding encoding
. The second form returns a copy of str
transcoded from src_encoding to dst_encoding. The last form returns a copy of str
transcoded to Encoding.default_internal
.
By default, the first and second form raise Encoding::UndefinedConversionError for characters that are undefined in the destination encoding, and Encoding::InvalidByteSequenceError for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings.
The options
keyword arguments give details for conversion. The arguments are:
- :invalid
-
If the value is
:replace
, #encode replaces invalid byte sequences instr
with the replacement character. The default is to raise the Encoding::InvalidByteSequenceError exception - :undef
-
If the value is
:replace
, #encode replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError. - :replace
-
Sets the replacement string to the given value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.
- :fallback
-
Sets the replacement string by the given object for undefined character. The object should be a Hash, a Proc, a Method, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.
- :xml
-
The value must be
:text
or:attr
. If the value is:text
#encode replaces undefined characters with their (upper-case hexadecimal) numeric character references. ‘&’, ‘<’, and ‘>’ are converted to “&”, “<”, and “>”, respectively. If the value is:attr
, #encode also quotes the replacement result (using ‘“’), and replaces ‘”’ with “"”. - :cr_newline
-
Replaces LF (“n”) with CR (“r”) if value is true.
- :crlf_newline
-
Replaces LF (“n”) with CRLF (“rn”) if value is true.
- :universal_newline
-
Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.
2877 2878 2879 2880 2881 2882 2883 |
# File 'transcode.c', line 2877
static VALUE
str_encode(int argc, VALUE *argv, VALUE str)
{
VALUE newstr = str;
int encidx = str_transcode(argc, argv, &newstr);
return encoded_dup(newstr, str, encidx);
}
|