Reason #104 • April 14th, 2026

ActiveSupport: String#truncate_bytes

The String#truncate method discussed yesterday is wonderful for truncating strings in the context of presenting text to users. However, when dealing with database columns, external APIs and other storage limits, we often have to think about bytes rather than characters. Luckily, we have String#truncate_bytes for this:

Ruby
text = "Año 😊 café"

text.length
# => 10

text.bytesize
# => 15

text.truncate_bytes(12, omission: "...")
# => "Año 😊..."
      
JavaScript
const encoder = new TextEncoder();
const text = "Año 😊 café";

const truncateBytes = (value, maxBytes, omission = "...") => {
  const omissionBytes = encoder.encode(omission).length;
  let result = "";

  for (const char of value) {
    const next = result + char;
    if (encoder.encode(next).length > maxBytes - omissionBytes) break;
    result = next;
  }

  return encoder.encode(value).length <= maxBytes ? value : result + omission;
};

encoder.encode(text).length;
// => 15

[...text].length;
// => 10

truncateBytes(text, 12);
// => "Año 😊..."
      

If you want to learn more about how grapheme clusters are used to figure out the boundaries between multibyte characters, check out Reason 28: String#grapheme_clusters.

History

truncate_bytes was added in Rails 6.0.0, released in 2019.

Reason #105 ?