rubyguides

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

  1. Thinking reverse! always returns self: It returns nil when no change occurs.

    s = "abc"
    s.reverse!  # => "cba"
    s.reverse!  # => nil (unchanged — empty or single char strings)
  2. Using reverse on non-string types: Call to_s first — reverse only works on strings.

    123.reverse   # => undefined method error
    123.to_s.reverse  # => "321"
  3. Assuming Unicode normalization: reverse does not decompose combined characters.

    "é".reverse  # => "é" — but depends on how the character is stored

See Also