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 strings
str1 = "Edpresso"
str2 = "is"
str3 = "awesome"
# get the length
a = str1.length
b = str2.length
c = str3.length
# print results
puts a
puts b
puts c

Explanation

  • Lines 2-4: We create and initialize string variables str1, str2, and str3. These are the strings whose length we want to get.

  • Lines 7-9: We get the length of the strings using the length method and store the results in variables a, b, and c.

  • 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.

Free Resources