String#empty?
str.empty? -> true or false Returns:
boolean · Updated March 13, 2026 · String Methods strings checking boolean
The empty? method checks whether a string contains any characters. It returns true if the string’s length is zero, and false otherwise.
Syntax
string.empty?
Parameters
This method takes no parameters.
Examples
Basic usage
"".empty?
# => true
"hello".empty?
# => false
Checking before operations
def greet(name)
name = name.strip
if name.empty?
"Hello, stranger!"
else
"Hello, #{name}!"
end
end
greet(" ")
# => "Hello, stranger!"
greet("Ada")
# => "Hello, Ada!"
Common Patterns
Form validation
def validate_form(name:, email:)
errors = []
if name.strip.empty?
errors << "Name is required"
end
if email.strip.empty?
errors << "Email is required"
end
errors
end
validate_form(name: " ", email: "ada@ruby.org")
# => ["Name is required"]
Conditional rendering
def render_sidebar(content)
if content.nil? || content.empty?
"<aside class=\"empty\">No content</aside>"
else
"<aside>#{content}</aside>"
end
end
Array filtering
strings = ["ruby", "", "rails", " ", "hanami"]
strings.reject(&:empty?)
# => ["ruby", "rails", " "]
strings.reject { |s| s.strip.empty? }
# => ["ruby", "rails", "hanami"]
Empty String vs Nil
Ruby distinguishes between empty string and nil:
"".nil? # => false
"".empty? # => true
nil.nil? # => true
nil.empty? # => NoMethodError (undefined method for nil)
# Use safe navigation operator with nil
nil&.empty? # => nil (returns nil instead of raising error)
The safe navigation operator (&.) is particularly useful when you’re unsure whether the variable might be nil.
Performance
The empty? method runs in O(1) constant time because Ruby stores string length as metadata. This is more efficient than comparing str.length == 0, though the difference is negligible for single checks.
Edge Cases
# Whitespace is not empty
" ".empty? # => false
"\n".empty? # => false
"\t".empty? # => false
# Use strip to handle whitespace
" ".strip.empty? # => true