How to Check if a String is Empty in Ruby
In Ruby, you can check if a string is empty by using the
empty? method, which returns true if the string has no characters. Alternatively, you can check if the string's length is zero with string.length == 0.Syntax
The main way to check if a string is empty in Ruby is by using the empty? method. It returns true if the string has no characters and false otherwise.
Another way is to check if the string's length is zero using string.length == 0.
ruby
string.empty?
string.length == 0Example
This example shows how to use empty? and length to check if strings are empty or not.
ruby
str1 = "" str2 = "hello" puts str1.empty? # true puts str2.empty? # false puts str1.length == 0 # true puts str2.length == 0 # false
Output
true
false
true
false
Common Pitfalls
One common mistake is to check if a string is empty by comparing it to nil. An empty string is not nil, so this check will fail.
Also, a string with only spaces is not empty. Use strip.empty? if you want to check for strings that are empty or only whitespace.
ruby
str = " " # Wrong way: puts str.nil? # false, string is not nil # Correct way to check empty or whitespace only: puts str.strip.empty? # true
Output
false
true
Quick Reference
| Method | Description | Returns |
|---|---|---|
| empty? | Checks if string has zero characters | true or false |
| length == 0 | Checks if string length is zero | true or false |
| strip.empty? | Checks if string is empty or only whitespace | true or false |
| nil? | Checks if object is nil (not empty) | true or false |
Key Takeaways
Use
empty? to check if a string has no characters.Checking
string.length == 0 is another way to find empty strings.An empty string is not the same as
nil.Use
strip.empty? to check for strings that are empty or only whitespace.Avoid comparing strings directly to
nil when checking for emptiness.