method

truncate_bytes

Importance_2
v7.1.3.4 - Show latest stable - 0 notes - Class: String
truncate_bytes(truncate_to, omission: "…") public

Truncates text to at most truncate_to bytes in length without breaking string encoding by splitting multibyte characters or breaking grapheme clusters (“perceptual characters”) by truncating at combining characters.

>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".size
=> 20
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".bytesize
=> 80
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".truncate_bytes(20)
=> "🔪🔪🔪🔪…"

The truncated text ends with the :omission string, defaulting to “…”, for a total length not exceeding truncate_to.

Raises ArgumentError when the bytesize of :omission exceeds truncate_to.

Show source
Register or log in to add new notes.