Unicode and encodings
suggest changeIn Ruby, strings are not just raw byte sequences; every String object carries both a sequence of bytes and an associated Encoding object. Ruby's encoding engine (M17N—Multilingualization) provides first-class support for Unicode (UTF-8, UTF-16, UTF-32) and dozens of legacy character encodings (ASCII-8BIT, ISO-8859-1, Windows-1252, Shift_JIS).
1. Characters vs. Bytes
In a multibyte encoding like UTF-8, a single character may occupy anywhere from 1 to 4 bytes:
greeting = "Café ☕"
# Number of logical characters
puts greeting.length #=> 6
puts greeting.size #=> 6
# Number of underlying bytes
puts greeting.bytesize #=> 9
# Associated encoding
puts greeting.encoding #=> UTF-8
Here, 'é' is encoded as 2 bytes (0xC3 0xA9), and the coffee emoji '☕' is encoded as 3 bytes (0xE2 0x98 0x95).
Inspecting Codepoints and Bytes
Ruby provides granular iterators to traverse strings at different levels of abstraction:
str = "Ruby 💎"
# Inspect raw byte values (decimal)
puts str.bytes.inspect
#=> [82, 117, 98, 121, 32, 240, 159, 146, 142]
# Inspect individual characters
puts str.chars.inspect
#=> ["R", "u", "b", "y", " ", "💎"]
# Inspect Unicode codepoints (hexadecimal)
str.each_codepoint do |cp|
printf("U+%04X ", cp)
end
# Output: U+0052 U+0075 U+0062 U+0079 U+0020 U+1F48E
2. Transcoding: encode vs. force_encoding
Understanding the difference between encode and force_encoding is vital:
encode(Transcoding): Changes the underlying bytes of the string so they represent the same characters in a new target encoding.force_encoding(Retagging): Keeps the underlying bytes identical and merely changes the encoding label attached to the string.
utf8_str = "résumé"
# 1. Transcode bytes from UTF-8 to ISO-8859-1 (Latin-1)
latin1_str = utf8_str.encode("ISO-8859-1")
puts latin1_str.encoding #=> ISO-8859-1
puts latin1_str.bytesize #=> 6 (1 byte per char in Latin-1)
# 2. force_encoding changes the label without changing bytes:
raw_binary = "\xC3\xA9".b # ASCII-8BIT (binary)
puts raw_binary.encoding #=> ASCII-8BIT
tagged_utf8 = raw_binary.force_encoding("UTF-8")
puts tagged_utf8 #=> "é"
puts tagged_utf8.encoding #=> UTF-8
Handling Unconvertible and Invalid Characters
When transcoding legacy data that contains characters unsupported by the destination encoding, configure replacement behavior:
unicode_text = "Price: €100 — Special!"
# Transcode to US-ASCII, replacing unconvertible characters with '?'
ascii_text = unicode_text.encode(
"US-ASCII",
invalid: :replace,
undef: :replace,
replace: "?"
)
puts ascii_text #=> "Price: ?100 ? Special!"
Validating Encodings
To check if a string contains valid bytes for its declared encoding:
bad_bytes = "Hello \xFF\xFE".force_encoding("UTF-8")
puts bad_bytes.valid_encoding? #=> false
# Clean invalid bytes
clean_str = bad_bytes.scrub("?")
puts clean_str #=> "Hello ??"
3. Unicode Normalization
In Unicode, characters with diacritics can be represented in two equivalent forms:
- Composed (NFC): A single precomposed codepoint (e.g.
U+00E9foré). - Decomposed (NFD): A base letter followed by a combining mark (e.g.
eU+0065+ combining acute accentU+0301).
Although visually identical, standard string comparison fails between different forms unless normalized:
nfc = "é" # "\u00E9"
nfd = "e\u0301" # "e" + combining accent
puts nfc == nfd #=> false (Different bytes and codepoints!)
# Normalize to Canonical Composition (NFC):
normalized_nfc = nfc.unicode_normalize(:nfc)
normalized_nfd = nfd.unicode_normalize(:nfc)
puts normalized_nfc == normalized_nfd #=> true
Available normalization forms:
:nfc(Canonical Composition - default, standard for web/databases):nfd(Canonical Decomposition):nfkc(Compatibility Composition):nfkd(Compatibility Decomposition)
4. Unicode-Aware Case Mapping
Since Ruby 2.4, standard case methods (upcase, downcase, capitalize, swapcase) support full Unicode case folding across all scripts:
puts "straße".upcase #=> "STRASSE" (German eszett)
puts "ΜΆΙΟΣ".downcase #=> "μάιοσ" (Greek; no final-sigma rule, so σ not ς)
puts "i".upcase(:turkic) #=> "İ" (Dotted capital I in Turkish)
5. Unicode Regular Expressions
Ruby's Onigmo regular expression engine supports Unicode character properties using \p{Property}:
text = "Ruby 3.3 was released on 2023-12-25! 🎉"
# Match any Unicode letter
letters = text.scan(/\p{L}+/)
puts letters.inspect #=> ["Ruby", "was", "released", "on"]
# Match any Unicode number
numbers = text.scan(/\p{N}+/)
puts numbers.inspect #=> ["3", "3", "2023", "12", "25"]
# Match emoji (\p{Emoji} would also match the digits 0-9)
emoji = text.scan(/\p{Extended_Pictographic}/)
puts emoji.inspect #=> ["🎉"]
6. File and IO Encodings
When opening files, you can specify both the file's encoding on disk (external encoding) and the encoding to transcode to in memory (internal encoding):
# Read a Latin-1 file and automatically convert it to UTF-8 in memory:
File.open('legacy_report.txt', 'r:ISO-8859-1:UTF-8') do |file|
file.each_line do |line|
puts line.encoding #=> UTF-8
end
end
Best Practices
- Default to UTF-8 Everywhere: Keep your source files, HTTP payloads, database connections, and file outputs consistently configured to UTF-8.
- Normalize Before Searching or Indexing: Use
str.unicode_normalize(:nfc)on external user inputs before comparing, indexing, or saving to databases. - Use
scrubto Sanitize Untrusted Inputs: PreventArgumentError: invalid byte sequence in UTF-8crashes by sanitizing incoming streams with.scrub.