Section 2.30. Removing Duplicate Characters


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"





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net