Fancy String Methods
Learn to Program, Third Edition — by Chris Pine (31 / 116)
👈 Chapter 5 Methods | TOC | More Arithmetic 👉
Let’s learn a few fun string methods. You don’t have to memorize them all; you can look up this page again if you forget them. I want to show you a small part of what strings can do. In fact, I can’t remember even half of the string methods myself — but that’s fine, because the Internet has great references with all of the string methods listed and explained. (I’ll show you where to find them in Chapter 15, Beyond This Book.) Actually, I don’t even want to know all the string methods. It’s kind of like knowing every word in the dictionary: I can speak English just fine without knowing every word in the dictionary.
The first string method is reverse, which returns a reversed version of the string:
1: var1 = "stop"
2: var2 = "deliver repaid desserts"
3: var3 = "....TCELES B HSUP - A magic spell?"
4:
5: puts var1.reverse
6: puts var2.reverse
7: puts var3.reverse
8: puts var1
9: puts var2
10: puts var3<= pots
stressed diaper reviled
?lleps cigam A - PUSH B SELECT....
stop
deliver repaid desserts
....TCELES B HSUP - A magic spell?
That third string is a spoiler from Final Fantasy 1 (or, as we called it at the time, Final Fantasy, back when the word “final” used to mean something). There’s a statute of limitations on spoilers, right?