October 2006
Intermediate to advanced
888 pages
16h 55m
English
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"Read now
Unlock full access