Ruby

String Length Ruby

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.

"Hello".length
=> 5

The method will return the characters in the string, including whitespace characters.

"Hello\t\r".length
=> 7

Method 2 – Size method

Ruby also has the size method, which will return the number of characters in the passed string.

"Hello".size
=> 5

Similar to the length method, it also includes all valid whitespace characters.

"Hello\t\r".size
=> 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.

string = ""
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:

$ ruby strings.rb
true

We can also use the empty method to check if a string is empty as follows:

string = ""
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.

string = "H e l l o w o r l d"
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.

string = "Hello"
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list