Home > Articles > Programming > Ruby

Working with Strings

📄 Contents

This chapter is from the book

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"

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.