String#reverse
String#reverse returns a new string with the characters in reverse order. The reverse! variant modifies the string in place.
Basic Usage
"hello".reverse
# => "olleh"
"Ruby".reverse
# => "ybuR"
In-place Reversal
reverse! modifies the string directly. Returns nil if the string is unchanged (empty or single character).
str = "hello"
str.reverse!
str # => "olleh"
Palindrome Check
A common pattern for checking if a string reads the same forwards and backwards:
def palindrome?(word)
word == word.reverse
end
palindrome?("racecar") # => true
palindrome?("hello") # => false
Character vs Byte Reversal
reverse operates on characters, not bytes. This matters for multi-byte encodings like UTF-8:
"héllo".reverse
# => "olléh"
"日本語".reverse
# => "語本日"
For byte-level reversal, convert to raw bytes first using encode('ASCII-8BIT').
Performance
For very long strings, reverse allocates a new string of equal size. The reverse! variant avoids one allocation but still copies all characters. Both are O(n) where n is the string length.
Common Mistakes
-
Thinking
reverse!always returnsself: It returnsnilwhen no change occurs.s = "abc" s.reverse! # => "cba" s.reverse! # => nil (unchanged — empty or single char strings) -
Using
reverseon non-string types: Callto_sfirst —reverseonly works on strings.123.reverse # => undefined method error 123.to_s.reverse # => "321" -
Assuming Unicode normalization:
reversedoes not decompose combined characters."é".reverse # => "é" — but depends on how the character is stored
See Also
- /reference/string-methods/string-strip/ — remove leading and trailing whitespace
- /reference/string-methods/string-scan/ — find all occurrences matching a pattern