How to Check if a String Is Empty in Ruby
empty? answers one question: does the string have no characters at all? It's true only for ''. A string of spaces isn't empty, so strip it first when spaces should count as nothing.
Syntax
<string>.empty?
<string>.strip.empty?
| Part | What it does |
|---|---|
.empty? | true when the string's length is zero. |
.strip | Returns the string without leading and trailing whitespace. |
The Ruby documentation for String describes empty? in one line: it "Returns whether the length of self is zero."
The Example
The example asks four strings whether they're empty: a name, an empty string, three spaces, and three spaces after strip.
Prerequisites
- Ruby. This guide uses Ruby 4.0.10.
Step 1: Write the Code
Create a file named main.rb:

puts 'Ada'.empty?
puts ''.empty?
puts ' '.empty?
puts ' '.strip.empty?
Step 2: Run It
ruby main.rb
false
true
false
true

Three spaces aren't empty until strip removes them. The command is the same in zsh, bash and PowerShell.
When the Value Might Be nil
nil isn't a string, so it has no empty?: calling it stopped the script with undefined method 'empty?' for nil (NoMethodError). Check for nil first, as in value.nil? || value.empty?, or read values with a default, such as ENV.fetch('NAME', ''), so you always get a string.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Calling empty? on nil | undefined method 'empty?' for nil (NoMethodError) | Check nil? first, or make sure you have a string |
Expecting ' '.empty? to be true | It's false: spaces are characters | Use strip.empty? |
Expecting blank? to exist | blank? comes from Rails, not plain Ruby | Use strip.empty? |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
NoMethodError on empty? | The value is nil | Find where it should have been set, or default it |
| A blank field passes the check | It holds spaces | Strip before checking |
FAQ
Does empty? work on arrays and hashes too?
Yes: [].empty? and {}.empty? are both true.
What's the safe navigation operator?
value&.empty? calls empty? only when value isn't nil, and gives nil otherwise.
Conclusion
string.empty? is true only for ''; add strip when spaces should count as empty, and make sure the value is a string, not nil, before you ask.
Additional Resources
- String, in the Ruby documentation.
