Library contents

Ruby String#bytesize

Measure the UTF-8 byte length of text that will be written to a file or sent in a message.

A simple example

String#bytesize

  1. Start with "é"
  2. Do this Encode in UTF-8
  3. Result 2 bytes
This single precomposed letter uses the bytes C3 and A9 in hexadecimal.
lesson.rb
value = "é"
puts(value.encode("UTF-8").bytesize)
Output
2

Syntax

Ruby syntax
value.encode("UTF-8").bytesize
Run these examples in Ruby

Save one example at a time as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Measure a café line on a receipt

A small device accepts an encoded label with a byte limit. Work with its actual encoding to determine what will be transmitted when the text contains more than plain ASCII.

From the programvalue = "café"
Result5
lesson.rb
value = "café"
puts(value.encode("UTF-8").bytesize)
Output
5

The letter é requires two UTF-8 bytes.

Advertisements

Budget space for a reaction icon

A messaging service budgets storage for reaction icons. Determine how many bytes one emoji occupies in the chosen encoding before reserving space in an outgoing message.

From the programvalue = "😀"
Result4
lesson.rb
value = "😀"
puts(value.encode("UTF-8").bytesize)
Output
4

The emoji occupies four UTF-8 bytes.

Count the bytes on a café tag

The word café ends in a precomposed accented character. Trace a UTF-8 round trip. How many bytes carry this label before it is decoded back to the original text?

Givencafé · UTF-8
Worked result5

What to watch for

Always identify the encoding. String length and encoded byte length can differ.

Documentation for String#bytesize