Skip to main content

How to Check if a String Is Empty in Ruby

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<string>.empty?
<string>.strip.empty?
PartWhat it does
.empty?true when the string's length is zero.
.stripReturns 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:

main.rb, which puts 'Ada'.empty?, ''.empty?, '   '.empty? and '   '.strip.empty?.

main.rb
puts 'Ada'.empty?
puts ''.empty?
puts ' '.empty?
puts ' '.strip.empty?

Step 2: Run It​

Terminal
ruby main.rb
Output
false
true
false
true

A zsh terminal where ruby main.rb prints false, true, false and 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​

MistakeWhat happensDo this instead
Calling empty? on nilundefined method 'empty?' for nil (NoMethodError)Check nil? first, or make sure you have a string
Expecting ' '.empty? to be trueIt's false: spaces are charactersUse strip.empty?
Expecting blank? to existblank? comes from Rails, not plain RubyUse strip.empty?

Troubleshooting​

SymptomLikely causeFix
NoMethodError on empty?The value is nilFind where it should have been set, or default it
A blank field passes the checkIt holds spacesStrip 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.