encode(*args) public

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 Hash gives details for conversion.


The hash options can have the following keys:


If the value is :replace, #encode replaces invalid byte sequences in str with the replacement character. The default is to raise the exception


If the value is :replace, #encode replaces characters which are undefined in the destination encoding with the replacement character.


Sets the replacement string to the value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.


Sets the replacement string by the hash for undefined character. Its key is a such undefined character encoded in source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.


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 “&amp;”, “&lt;”, and “&gt;”, respectively. If the value is :attr, #encode also quotes the replacement result (using ‘“’), and replaces ‘”’ with “&quot;”.


Replaces LF (“n”) with CR (“r”) if value is true.


Replaces LF (“n”) with CRLF (“rn”) if value is true.


Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.

Show source
Register or log in to add new notes.
February 25, 2013 - (v1_9_3_125)
1 thank

Using the undef/replace param overwrites the fallback parameter

If you want to provide a fallback Hash / Proc / Object you must not define the :undef and/or replace params since they overwrite the fallback.

How fallback works

fallback = Hash.new { '?' }
fallback["\u2014"] = "-"
"\u2014".encode!("ISO-8859-15", fallback: fallback)
=> "-"

Undef overwrites fallback:

fallback = Hash.new { '?' }
fallback["\u2014"] = "-"
"\u2014".encode!("ISO-8859-15", fallback: fallback, undef: :replace, replace: '?' )
=> "?"