Stringy Superpowers

I’d really feel like I was doing you a disservice if I didn’t show you at least a little more of what strings can do (in Ruby, at least). Plus, if I do, I can give you more interesting exercises. Mind you, I’m still not going to show you even half, but I’ve just got to show you a little more.

Remember back here when I said a lot of the string methods also work on arrays? Well, it goes both ways: some of the array methods you’ve learned also work on strings.

Perhaps the most important and versatile is the […] method. The first thing you can do with it is pass in a number and get the character at that position in the string:

da_man = ​'Mr. T'
big_T = da_man[4]
puts big_T
T

And then you can do fun stuff like this:

puts ...

Get Learn to Program, 2nd 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.