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 stringsstr1 = "Google"str2 = "Netflix"str3 = "Amazon"str4 = "Apple"str5 = "Meta"# get the sizesa = str1.sizeb = str2.sizec = str3.sized = str4.sizee = str5.size# print resultsputs aputs bputs cputs dputs e
Code explanation
-
Lines 2–6: We create the string variables whose size we want to get.
-
Lines 9–13: We call the
sizemethod on the strings we created. The results are stored on variablesa,b,c, andd. -
Lines 16–20: We print the results to the console.