How to check if a string has a length of zero in Ruby

There are several ways to see if a string has a length of 0 in Ruby. A string with length 0 is an empty string. We can use either of the two methods below:

  1. length method
  2. Compare with ""

Length function

The length function returns the length of a string. We can compare if the length of the string is 0. If it is 0, the string is empty. Otherwise, the string is not empty.

Example

The following code snippet shows how to check if the length of a string is 0 using the length method in Ruby:

my_string = ""
if my_string.length == 0
puts "String is empty"
else
puts "String is not empty"
end

Comparing with ""

We can also check if the string equals "". If this is true, the string is empty. Otherwise, the string is not empty.

Example

The following code snippet shows how to check if the length of a string is 0 through comparison with "":

my_string = ""
if my_string == ""
puts "String is empty"
else
puts "String is not empty"
end

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved