Character encoding determines how a sequence of bytes maps to textual characters. Because every Ruby string consists of bytes, its encoding determines how many bytes represent each character and which characters those bytes denote. section 8.1.6
Ruby exposes encoding at several boundaries:
- Ruby source files default to UTF-8; __ENCODING__ reports the source encoding, while a magic comment such as # encoding: ASCII changes it. section 8.1.7
- Individual strings report their encoding through encoding and can be transcoded with encode or encode!, provided the conversion is permitted. section 8.1.7
- force_encoding bypasses permitted-conversion checks and labels the existing bytes with the specified encoding; it does not perform the same conversion as encode. section 8.1.7
- File input can be read character-wise with getc or byte-wise with getbyte; these operations may return different results when characters occupy multiple bytes. section 12.2.3
Transcoding versus relabeling
A string such as str = "Test string" reports UTF-8 through str.encoding. Calling str.encode("US-ASCII") produces a converted string, while str.encode!("US-ASCII") changes str itself. force_encoding is different: it assigns an encoding to the current byte sequence, which can affect how later characters are interpreted. section 8.1.7
>> str = "Test string"
=> "Test string"
>> str.encoding
=> #<Encoding:UTF-8>
Inspect a Ruby string's encoding directly before experimenting with transcoding or byte-level operations. section 8.1.7




