How to get the size of a string in bytes in Ruby

Overview

bytesize is a method in Ruby that is used to count the number of bytes in a string. It gets the length of a string in bytes.

Syntax

str.bytesize

Parameters

bytesize does not take any parameters.

Return value

The value returned is an integer value that represents the count of bytes in a string.

Code example

In the code below, we will create some strings and get their sizes in bytes.

# create strings
str1 = "Edpresso"
str2 = "is"
str3 = "the best"
# get the bytes sizes
a = str1.bytesize
b = str2.bytesize
c = str3.bytesize
# print out returned values
puts a
puts b
puts c

Free Resources