We can use Ruby to get the length of a String by using either the String length method or the size method. The length method will return the length of the string, and if the string is empty, it will return 0. Let’s take a look at the length method first.
string_length = "This is a String".length
The above code would return the number 16.
Some other examples of length method are below:
string_1 = "This-is-a-String".length;
string_2 = "ThisisaString".length;
string_3 = "".length;
string_4 = "This String has numbers 01239".length;
puts string_1
puts string_2
puts string_3
puts string_4
#Output
16
13
0
29
Let’s take a look at getting the String length in Ruby using the size method.
Using Ruby to Get String Length Using the Size Method
We can also use the size method in Ruby to get the length of a string, just as we used the length method above.
string_length = "This is a String".size
The above code would return the number 16.
Some other examples of size method are below:
string_1 = "This-is-a-String".size;
string_2 = "ThisisaString".size;
string_3 = "".size;
string_4 = "This String has numbers 01239".size;
puts string_1
puts string_2
puts string_3
puts string_4
#Output
16
13
0
29
Hopefully this article has been useful to help you understand how to use Ruby to get string length.