2.29. Reversing a String

A string may be reversed simply by using the reverse method (or its in-place counterpart reverse!):

s1 = "Star Trek"
s2 = s1.reverse         # "kerT ratS"
s1.reverse!             # s1 is now "kerT ratS"

Suppose that you want to reverse the word order (rather than character order). You can use String#split, which gives you an array of words. The Array class also has a reverse method; so you can then reverse the array and join to make a new string:

phrase = "Now here's a sentence"
phrase.split(" ").reverse.join(" ")
# "sentence a here's Now"

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.