Ruby’s String#force_encoding assigns a new encoding to a string’s existing bytes without converting or validating those bytes. Unlike encode, it bypasses compatibility checks and applies the requested encoding unconditionally. section 8.1.7
Use force_encoding when byte-level processing produces a string whose encoding metadata needs to be restored:
- A custom String#^ implementation XORs corresponding bytes, packs them into a string, and calls force_encoding(self.encoding) so the result uses the original string’s encoding. section 10.11.3
- Do not confuse force_encoding with encode: encode performs permitted transcoding, while force_encoding changes the interpretation assigned to the existing byte sequence. section 8.1.7
Restoring an XOR result’s encoding
class String def ^(key) kenum = key.each_byte.cycle each_byte.map { |byte| byte ^ kenum.next }.pack("C*").force_encoding(self.encoding) end end The byte sequence created by map and pack is therefore labeled with the receiver’s original encoding. section 10.11.3
each_byte.map {|byte| byte ^ kenum.next }.pack("C*").
force_encoding(self.encoding)
Inspect the complete byte-wise XOR expression, including pack("C*") and force_encoding(self.encoding). section 10.11.3
