Length of the string is defined as the number of characters in the string. To get the length of a given string in Ruby, you can use the length
method or the size
method.
If given string is in x
, then x.length
returns the length of the string.
If given string is in x
, then x.size
returns the length of the string.
In this example,
str1
with a string value of "Hello World"
.length
method of the str1
string object to get the length of the string and store the returned value in the variable length1
.length1
to the console using puts
method.# Length of "Hello World" String
str1 = "Hello World"
length1 = str1.length
puts "Length of given string is: #{length1}"
Length of given string is: 11
In this example,
str2
with a string value of "apple"
.size
method of the str2
string object to get the length of the string and store the returned value in the variable length2
.length2
to the console using puts
method.# Length of "apple" String
str2 = "apple"
length2 = str2.size
puts "Length of given string is: #{length2}"
Length of given string is: 5
In this tutorial, we learned How to get Length of String in Ruby language using length
method or size
method of string object, with well detailed examples.