rubyguides

String#empty?

str.empty? -> true or false

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

The method takes no parameters and operates on the receiver string directly. It inspects the string’s internal length field, which Ruby stores as metadata alongside the character data, so the check completes in constant time regardless of the string’s size. Because no allocation or traversal happens, empty? is safe to call inside tight loops and performance-sensitive paths.

Examples

Basic usage

"".empty?
# => true

"hello".empty?
# => false

The two examples above show the simplest case: a literal empty string returns true, and any string with characters returns false. This is the most direct way to ask whether a string contains anything at all. The method runs in constant time because Ruby stores the length as metadata, so calling it repeatedly in a loop carries no hidden cost.

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!"

The greet method demonstrates a common guard pattern: strip whitespace first, then check for emptiness. This two-step approach handles cases where the input is all spaces, a single newline, or genuinely blank. The pattern appears throughout Ruby applications because it is a concise way to reject missing input without writing a custom validation method for each field.

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"]

Notice that strip.empty? is called before evaluating whether the field is blank. This is important because a user might type spaces into a form field, and the application should treat that as missing input rather than valid data. Calling strip first normalises the input so the empty? check is meaningful.

Conditional rendering

def render_sidebar(content)
  if content.nil? || content.empty?
    "<aside class=\"empty\">No content</aside>"
  else
    "<aside>#{content}</aside>"
  end
end

The conditional rendering pattern uses nil? alongside empty? to cover both absence and emptiness in a single guard. When content is nil, the || short-circuits and the first branch fires; when content is an empty string, empty? catches it. This is a compact way to write a default for missing data without a separate if block.

Array filtering

strings = ["ruby", "", "rails", "   ", "hanami"]

strings.reject(&:empty?)
# => ["ruby", "rails", "   "]

strings.reject { |s| s.strip.empty? }
# => ["ruby", "rails", "hanami"]

Using reject(&:empty?) is concise, but it only removes empty strings — strings that contain only whitespace will stay in the array. The second form with strip.empty? handles both cases, which is important when the strings come from user input or file parsing. Choosing between the two depends on whether whitespace-only values are meaningful in your context.

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.

checking for an empty string directly

empty? is the clearest way to ask whether a string has no characters at all. It keeps the condition explicit and avoids making the reader infer that a length comparison means the same thing. That can make form validation and guard clauses easier to scan, especially when the code wants to reject blank input before doing anything else.

The method is also a good reminder that empty and nil are different states. A string can be empty and still be present, which is often important in application code. By using empty?, the branch stays focused on the exact condition the program cares about.

That distinction keeps validation logic honest because the code can reject blank input without accidentally treating every missing value the same way. It is a small method, but it helps the program describe the state it actually found instead of guessing based on a broader truthy check. That precision makes the branch easier to support later.

It also makes common guards read very naturally because the caller can ask for emptiness directly instead of checking length or inventing a second condition. That keeps the code short and avoids turning a simple question into a longer expression. When the branch needs to know whether there is anything to work with, empty? is the direct answer.

Edge Cases

# Whitespace is not empty
" ".empty?      # => false
"\n".empty?     # => false
"\t".empty?     # => false

# Use strip to handle whitespace
" ".strip.empty? # => true

Choosing the right emptiness check

For most Ruby code, empty? is the idiomatic choice when you need to know whether a value has no characters. If you also need to reject whitespace-only input, pair it with strip first. For collections, empty? works the same way on arrays and hashes, so the method name reads consistently across types. When the value might be nil, the safe navigation operator &. keeps the check concise without an extra guard clause.

See Also