Strings are an array of characters enclosed in single or double-quotes. Strings are fundamental building blocks in programming because they allow us to accept or display information to and from programs.
A string length refers to the number of characters in a string literal. Valid string characters can include alphanumeric characters and symbols.
In this short guide, we will discuss how to use various methods to get the length of a string.
Method 1 – Length method
The simplest way to get the length of a string is to use Ruby’s built-in length method. It returns the length of the characters in the specified string.
=> 5
The method will return the characters in the string, including whitespace characters.
=> 7
Method 2 – Size method
Ruby also has the size method, which will return the number of characters in the passed string.
=> 5
Similar to the length method, it also includes all valid whitespace characters.
=> 7
Check If a String is Empty
Using the built-in ruby methods discussed above, we can check if a string is empty. If the length equals 0, then the string is empty; otherwise, the string is not empty.
def is_empty(str)
if str.size == 0
return true
else
return false
end
end
puts (is_empty(string))
We can pass any string to the function, and it will evaluate if the string is empty or not.
Example output from the above code is below:
true
We can also use the empty method to check if a string is empty as follows:
puts string.empty?
Convert String to an Array of Characters
You can also convert a string into an array of words.
To convert a string into an array, use the split method.
new_array = string.split
puts new_array
Break a String Into Individual Characters
In the example above, the split method will create an array of words separated by a space. However, we can create an array of individual characters.
We do this by iterating over each item of the string and append it to an array.
array = []
string.each_char {|ch| array.push(ch)}
puts array
The code above will return all the characters in the string as an array.
Conclusion
In this guide, we discussed how to work with strings and fetch the length of a string.