String#bytesize

str.bytesize -> integer
Returns: Integer · Updated March 13, 2026 · String Methods
string bytes encoding bytesize

String#bytesize returns the number of bytes in a string when encoded. This differs from length because multi-byte characters (like UTF-8 encoded non-ASCII characters) use more than one byte per character.

Syntax

string.bytesize

Parameters

This method takes no parameters.

Examples

Basic ASCII usage

hello = "Hello"
hello.bytesize
# => 5

UTF-8 characters

greeting = "こんにちは"
greeting.length
# => 5

greeting.bytesize
# => 15 (each character is 3 bytes in UTF-8)

Mixed content

ascii = "ruby"
ascii.length   # => 4
ascii.bytesize # => 4

utf8 = "rüby"
utf8.length   # => 4
utf8.bytesize # => 5 (ü = 2 bytes in UTF-8)

emoji = "🎉"
emoji.length   # => 1
emoji.bytesize # => 4 (emoji are 4 bytes in UTF-8)

Common Patterns

Check string encoding size for storage

def fits_in_column?(text, max_bytes)
  text.bytesize <= max_bytes
end

fits_in_column?("Hello", 255)
# => true

fits_in_column?("こんにちは", 255)
# => true (15 bytes)

fits_in_column?("a" * 300, 255)
# => false

Calculate string memory usage

text = "Hello World"
memory_bytes = text.bytesize + 8  # +8 for string object overhead estimate
# => 19

Handle encoding in API calls

# Many APIs have byte limits, not character limits
def within_byte_limit?(text, limit)
  text.bytesize <= limit
end

Performance Notes

bytesize runs in O(1) constant time because the byte count is cached in the string object.

Errors

This method never raises an error. It works on any string object and returns an integer, even for empty strings:

"".bytesize
# => 0

See Also