String#swapcase
str.swapcase -> string String · Added in v1.0 · Updated March 13, 2026 · String Methods 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.
Syntax
string.swapcase
Parameters
.swapcase takes no parameters. The transformation applies to the entire string.
Examples
Basic usage
"Hello World".swapcase
# => "hELLO wORLD"
"Ruby Guides".swapcase
# => "rUBY gUIDES"
"123 ABC def".swapcase
# => "123 abc DEF"
Non‑alphabetic characters unchanged
"@#\$%^&*()".swapcase
# => "@#\$%^&*()"
"123".swapcase
# => "123"
Using .swapcase! to modify in place
text = "Mixed CASE"
text.swapcase!
puts text # => "mIXED case"
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)
Common Patterns
Toggling case of user input
input = "Toggle This"
toggled = input.swapcase
puts toggled # => "tOGGLE tHIS"
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.)
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
Combining with other string methods
" Hello Ruby ".swapcase.strip
# => "hELLO rUBY"
"hello".swapcase.capitalize
# => "Hello"
Errors
.swapcase does not raise errors for any input. It returns a new string even for empty strings:
"".swapcase
# => ""
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"