Reverse a String in Ruby
How Ruby's String#reverse works, where it breaks accents and emoji, and how to reverse by grapheme or by word while keeping text usable.
Ruby's built-in String#reverse is the quickest way to flip text. It is reliable for plain ASCII and most precomposed accented letters. With decomposed accents, emoji sequences, binary data or right-to-left scripts, it can produce output that looks wrong or no longer means the same thing. This review covers what the method changes, where it falls short, and when the reversed result is not a good fit for readers.
Is reversing a string in Ruby suitable for your use?
Recommendation: use String#reverse for program logic, such as palindrome checks, algorithm exercises, test fixtures, or building keys for suffix matching. Its main benefit is that it is built in, needs no dependencies, and works on characters rather than bytes for normally encoded strings. The deciding tradeoff is that "character" in Ruby means code point, not what a reader sees as one letter or symbol. For user-facing text, switch to grapheme-aware reversal, or reconsider whether reversal is needed at all.
Keep plain text when people need to read, search, copy, quote, or hear the content through assistive technology. Reversed text works as a puzzle, a decoration, or an internal value. It does not replace the original.
What String#reverse actually changes
String#reverse returns a new string. It contains the same characters as the original, stored in the opposite order. The original string is left untouched. String#reverse! performs the same reversal in place and returns the modified receiver. This is a change to the stored data. It is not a visual effect: no glyphs are mirrored, no CSS is applied, and no bidirectional display control is involved. Copy the result and you get the reversed characters.
"hello".reverse # => "olleh"
s = +"abc"
s.reverse!
s # => "cba"
# With the frozen_string_literal: true magic comment,
# literals are frozen and reverse! raises FrozenError:
"abc".reverse! # FrozenError
The word "reverse" gets used loosely, so it helps to separate it from related ideas. Character reversal, which is what this method does, flips the order of code points. Word reversal flips the order of words and leaves each word readable. Mirror text, upside-down text and "reverse fonts" are different again. They either substitute look-alike Unicode characters or apply a visual transform at display time, and String#reverse does neither.
Reversing words instead of characters
To reverse word order, split the string, reverse the resulting array, and join it back together. Plain split with no arguments collapses runs of whitespace and drops leading and trailing spaces. If the original spacing matters, split on a capturing whitespace pattern so the separators are kept.
"hello big world".split.reverse.join(" ")
# => "world big hello" (double space lost)
"hello big world".split(/(\s+)/).reverse.join
# => "world big hello" (original spacing kept)
Code points versus visible characters
For a UTF-8 string, reverse works on code points. Many things a reader sees as one character are actually several code points. Examples include a letter followed by a combining accent, an emoji with a skin-tone modifier, a flag made from two regional indicator symbols, and family or profession emoji joined with zero-width joiners. Reversing code points pulls these sequences apart or puts their pieces in the wrong order.
composed = "caf\u00e9" # é as one code point
composed.reverse # => "éfac" (fine)
decomposed = "cafe\u0301" # e + combining acute accent
decomposed.length # => 5
decomposed.reverse # => "\u0301efac" (accent now leads, detached)
"👍🏽".reverse.codepoints.map { |c| c.to_s(16) }
# => ["1f3fd", "1f44d"] (skin-tone modifier now precedes the thumb)
The fix is to reverse by grapheme cluster. Ruby 2.5 and later provide String#grapheme_clusters. A grapheme cluster is the unit Unicode defines as a user-perceived character. Reversing an array of clusters keeps accents attached to their letters and keeps emoji sequences intact.
"cafe\u0301".grapheme_clusters.reverse.join
# => "e\u0301fac" (displays as "éfac")
"👍🏽 ok".grapheme_clusters.reverse.join
# => "ko 👍🏽"
# Equivalent using the extended grapheme regex:
"cafe\u0301".scan(/\X/).reverse.join
Normalizing to NFC with unicode_normalize(:nfc) before reversing merges many letter-plus-accent pairs into single code points. That makes plain reverse safe for those specific cases. It does not help with emoji sequences, or with combinations that have no precomposed form, so grapheme-based reversal is the more general solution.
Even grapheme reversal changes meaning for some sequences. Reversing the clusters inside a flag is not an issue, because the flag is a single cluster. Reversing the code points inside a flag, which is what plain reverse does, swaps the two regional indicators. The result may be a different country's flag, or two separate letter symbols. What actually appears depends on the font and platform, and this was not tested across environments here.
Binary strings and encodings
If a string is tagged as binary (ASCII-8BIT), reverse operates on bytes. Reversing the bytes of multibyte UTF-8 text yields invalid sequences. Confirm the encoding before reversing data that came from files, sockets, or other external sources.
"€".b.reverse.force_encoding("UTF-8").valid_encoding?
# => false
Right-to-left scripts
Arabic and Hebrew text is stored in logical order, and display engines lay it out right to left using the Unicode bidirectional algorithm. Calling reverse on such text does not "fix" its direction. It changes the stored order, so the displayed result is garbled. Text containing a mix of directions is even more likely to come out confusing. If the actual goal is to control display direction, handle that in the presentation layer instead of altering the string.
Will reversed text stay readable after copying or sharing?
Because reverse changes the stored characters, copying and pasting carries the reversed order with it. That has a few practical consequences:
- Reading order: anyone reading the copied text sees the reversed sequence. Nothing reverts it automatically.
- Assistive technology: screen readers work from the stored text, so reversed words are likely to be announced as unfamiliar strings. No specific screen reader was tested for this review.
- Search: reversed text will not match searches for the original words, in your own application or anywhere else.
- Editing: cursor movement and selection follow stored order. Fixing a typo in reversed text means working backwards.
- Broken sequences: code-point reversal can leave combining marks or emoji modifiers standing alone. How they render varies by font and platform and was not verified in specific environments.
If reversed text is shown to people for decoration, a game, or a visual effect, keep the original string available. In a web page, that could be an accessible label carrying the readable version. In data, it could be a separate field. Whenever the content carries meaning someone needs to act on, provide the plain-text equivalent.
Choosing the right approach
| Goal | Approach | Main caveat |
| Reverse ASCII or simple text in code | str.reverse | Splits multi-code-point characters |
| Reverse text people will see | str.grapheme_clusters.reverse.join | Requires Ruby 2.5 or later |
| Reverse word order | str.split(/(\s+)/).reverse.join | Punctuation stays attached to its word |
| Modify the string in place | str.reverse! | Raises FrozenError on frozen strings |
| Check for a palindrome | s == s.reverse after normalizing case | Combining marks and emoji need grapheme handling |
Open questions this review does not settle
This review relies on documented Ruby behavior and on Unicode's definitions of code points and grapheme clusters. It does not include rendering tests on particular operating systems, browsers, messaging apps, or screen readers, and it makes no performance measurements. If your output goes to a specific destination or must support a specific assistive technology, test that combination directly before depending on it.