What is the string.size method in Ruby?

Overview

The size method of a string is used to get the number of characters present in a string. It returns an integer value.

Syntax

str.size

Parameters

str: This is the string whose size or number of characters we want to find.

Return value

The value returned is an integer that represents the number of characters present in a string.

Code example

# create strings
str1 = "Google"
str2 = "Netflix"
str3 = "Amazon"
str4 = "Apple"
str5 = "Meta"
# get the sizes
a = str1.size
b = str2.size
c = str3.size
d = str4.size
e = str5.size
# print results
puts a
puts b
puts c
puts d
puts e

Code explanation

  • Lines 2–6: We create the string variables whose size we want to get.

  • Lines 9–13: We call the size method on the strings we created. The results are stored on variables a, b, c, and d.

  • Lines 16–20: We print the results to the console.

Free Resources