String#swapcase
str.swapcase -> string The .swapcase method returns a new string where all uppercase letters are converted to lowercase and all lowercase letters are converted to uppercase. Non-alphabetic characters (digits, symbols, whitespace) remain unchanged. The original string is not modified; use .swapcase! for an in-place transformation.
This method is useful for creating case‑toggled versions of text, formatting headings with alternating case, or normalizing case‑variant data. It operates on a per‑character basis without considering locale or Unicode case‑mapping rules beyond the ASCII range.
That makes swapcase predictable in simple text-processing jobs, but it also means you should not use it as a general-purpose language translation tool. If the text includes accented or locale-specific characters, test the result instead of assuming it will mirror a human reader’s expectations.
Syntax
string.swapcase
Parameters
.swapcase takes no parameters. The transformation applies to the entire string.
Before the examples, it helps to keep that scope in mind: the method touches every character in the string, but only alphabetic characters actually change. That makes the behavior easy to predict when you are reading through the sample output below.
Examples
Basic usage
"Hello World".swapcase
# => "hELLO wORLD"
"Ruby Guides".swapcase
# => "rUBY gUIDES"
"123 ABC def".swapcase
# => "123 abc DEF"
These examples show the core rule: letters flip case one by one, while the rest of the string stays exactly as it was. If you are scanning logs or user input, this can make a string easier to compare without changing punctuation or spacing.
That consistency is what makes swapcase easy to reason about in small scripts. You can look at the output and immediately see which parts were alphabetic, without worrying that the method also moved separators or trimmed the string.
Non‑alphabetic characters unchanged
"@#\$%^&*()".swapcase
# => "@#\$%^&*()"
"123".swapcase
# => "123"
The unchanged output is important when the string contains IDs, punctuation, or formatting characters that should not move. swapcase only touches alphabetic characters, so it stays narrow in scope.
If you are using it in a pipeline, this narrow scope is a plus. It means the method is safe to drop into a chain without changing delimiters or whitespace that other steps might depend on.
Using .swapcase! to modify in place
text = "Mixed CASE"
text.swapcase!
puts text # => "mIXED case"
Use the bang version when you want to mutate the same object, such as when a value is stored in a variable that gets reused later. That is the main tradeoff: a smaller allocation footprint in exchange for changing the original string.
In practice, the non-bang form is usually the safer default because it avoids side effects. Reach for .swapcase! only when the calling code expects the original string object to change.
Unicode characters
.swapcase only affects ASCII letters A‑Z and a‑z. Unicode letters outside this range are left unchanged:
"café École".swapcase
# => "CAFÉ éCOLE"
# (the accent remains; only 'c', 'a', 'f', 'É', 'c', 'o', 'l', 'e' swap)
This is a useful reminder that Ruby’s string methods can behave differently once Unicode enters the picture. For mixed-language text, review the output carefully before using it in a user-facing display.
If your application handles multilingual text, treat this as a targeted text tweak rather than a full locale-aware transformation. That keeps expectations realistic and makes the method easier to test.
Common Patterns
Toggling case of user input
input = "Toggle This"
toggled = input.swapcase
puts toggled # => "tOGGLE tHIS"
A quick visual change like that is handy in small utilities or demonstrations because you can see the effect immediately without reformatting the whole string. It is less about business logic and more about quick, visible transformation.
One benefit of the reversible behavior is that it works well in before-and-after examples. The reader can see the effect immediately without needing any extra setup.
Creating alternating‑case headings
title = "important announcement"
alternating = title.swapcase
puts alternating # => "IMPORTANT ANNOUNCEMENT"
# (Note: this yields all‑uppercase because the original was all‑lowercase.
# For true alternating case, combine with other transformations.)
The example above shows that swapcase is not the same as a stylistic text effect. It flips whatever case already exists, so it is best for mirroring or toggling text rather than generating a specific visual pattern.
That difference matters when you are trying to design output for humans. If you need a controlled headline style, use dedicated formatting logic instead of relying on the existing capitalization pattern.
Normalizing case‑variant data
When data may have been entered with accidental Caps Lock, you can use .swapcase to detect and possibly correct it:
def maybe_caps_lock?(str)
str == str.swapcase && str =~ /[A-Za-z]/
end
maybe_caps_lock?("hELLO") # => true
maybe_caps_lock?("Hello") # => false
The check is intentionally simple: it compares the original string to its swapped version and confirms that at least one ASCII letter is present. That is enough for a lightweight heuristic, even though it is not a full language-aware detector.
You can think of it as a quick signal, not a final answer. In code review terms, that is usually enough for a helper method as long as the limitation is documented in the call site.
Combining with other string methods
" Hello Ruby ".swapcase.strip
# => "hELLO rUBY"
"hello".swapcase.capitalize
# => "Hello"
Combining methods can narrow the exact output you want. swapcase handles the letter flipping, and the second method finishes the formatting pass, which is often easier to read than writing custom character logic.
This also keeps the example close to normal Ruby style. Small method chains are easier to follow than a custom loop when the transformation is just a couple of simple text operations.
Errors
.swapcase does not raise errors for any input. It returns a new string even for empty strings:
"".swapcase
# => ""
As a result, the method is easy to use in pipelines because you do not need a special case for blank input. The result is still a string, so later calls can continue normally.
In data-cleaning code, that convenience matters because empty values often appear in the middle of a larger collection. You can apply swapcase consistently and let the rest of the pipeline handle the result.
The bang version .swapcase! returns nil if no changes were made (i.e., the string contained no alphabetic characters):
s = "123"
s.swapcase! # => nil
s # => "123"
When .swapcase! returns nil, that is a standard Ruby signal that nothing changed. If your code branches on the return value, keep that in mind so you do not mistake a no-op for a failure.