What is string.length in Ruby?
Overview
Getting the length of a string in Ruby is easy. The length method of a string can be used to achieve this.
The length method returns the count of characters present in a string.
Syntax
str.length
Where str is the string whose length we want to get.
Parameters
This method doesn’t take any parameters
Return value
The return value is an integer. This value represents the number of characters present in the string.
Code example
# create stringsstr1 = "Edpresso"str2 = "is"str3 = "awesome"# get the lengtha = str1.lengthb = str2.lengthc = str3.length# print resultsputs aputs bputs c
Explanation
-
Lines 2-4: We create and initialize string variables
str1,str2, andstr3. These are the strings whose length we want to get. -
Lines 7-9: We get the length of the strings using the
lengthmethod and store the results in variablesa,b, andc. -
Lines 12-14: We print the results.
As we can see, our results are integer values that represent the number of characters each string contains.