Fancy String Methods

Let’s learn a few fun string methods. You don’t have to memorize them all; you can just look up this page again if you forget them. I just 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 you can find great references on the Internet with all the string methods listed and explained. (I will show you where to find them in Chapter 15, Beyond This Fine Book.) Really, 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. (And isn’t that really the whole point of the dictionary? You don’t have to know what’s in it.)

Our first string method is reverse, which returns a reversed version of the string:

var1 = ​'stop'
var2 = ​'deliver repaid desserts'
var3 = ​'....TCELES B HSUP A magic spell?'
puts var1.reverse
puts var2.reverse
puts var3.reverse
puts var1
puts var2
puts var3
pots
stressed diaper reviled
?lleps cigam A PUSH B SELECT....
stop
deliver repaid desserts
....TCELES B HSUP A magic spell?

As you can see, reverse doesn’t change the original string; it just makes a new backward version of it. That’s why var1 is still 'stop' even after we called reverse on it.

Another string method is length, which tells us the number of characters (including spaces) in the string:

puts ​'What is your full name?'
name = gets.chomp
puts ​'Did you know there are '​ + name.length + ​' characters'
puts ​'in your name, '​ + name + ​'?'
<= What is your full name?
=> Christopher David Pine
<= example.rb:3:in `+': no implicit conversion of Fixnum into String (TypeError)
  from example.rb:3:in `<main>'

Uh-oh! See? There it is! It’s an easy mistake to make. Anyway, if you didn’t know to be on the lookout for this error, you can still figure that the problem must have happened sometime after the line name = gets.chomp, since I was able to type my name. See whether you can figure it out.

The problem is with length: it gives us an integer, but we want a string. That’s easy enough; we’ll just throw in a .to_s (and cross our fingers):

puts ​'What is your full name?'
name = gets.chomp
puts ​'Did you know there are '​ + name.length.to_s + ​' characters'
puts ​'in your name, '​ + name + ​'?'
<= What is your full name?
=> Christopher David Pine
<= Did you know there are 22 characters
 in your name, Christopher David Pine?

No, I did not know that. Note: 22 is the number of characters in my name, not the number of letters (count ’em). I guess we could write a program that asks for your first, middle, and last names individually and then adds those lengths together—hey, why don’t you do that? Go ahead, I’ll wait.

Did you do it? Right on.

Well, unless your name is Bjørn or Håvard, in which case you had some problems. Ruby is expecting only ASCII characters (basically the stuff you can type on an American keyboard—the A in ASCII stands for American). It is possible to use any character in any language, but it requires some extra work and is just more advanced than what we’re going to cover.

So, a number of string methods can also change the case (uppercase and lowercase) of your string. upcase changes every lowercase letter to uppercase, and downcase changes every uppercase letter to lowercase. swapcase switches the case of every letter in the string, and finally, capitalize is just like downcase, except it switches the first character to uppercase (if it’s a letter).

letters = ​'aAbBcCdDeE'
puts letters.upcase
puts letters.downcase
puts letters.swapcase
puts letters.capitalize
puts ​' a'​.capitalize
puts letters
AABBCCDDEE
aabbccddee
AaBbCcDdEe
Aabbccddee
a
aAbBcCdDeE

As you can see from the line puts ' a'.capitalize, the capitalize method capitalizes only the first character, not the first letter. Also, as we have seen before, throughout all of these method calls, letters remains unchanged. I don’t mean to belabor the point, but it’s important to understand. Some methods do change the associated object, but we haven’t seen any yet, and we won’t for some time.

The last of the fancy string methods we’ll look at do visual formatting. The first, center, adds spaces to the beginning and end of the string to make it centered. However, just like you have to tell the puts method what you want it to print and you have to tell the + method what you want it to add, you have to tell the center method how wide you want your centered string to be.

So if I wanted to center the lines of a poem, I would do it like this:

line_width = 50
puts( ​'Old Mother Hubbard'​.center(line_width))
puts( ​'Sat in her cupboard'​.center(line_width))
puts( ​'Eating her curds and whey,'​.center(line_width))
puts( ​'When along came a spider'​.center(line_width))
puts( ​'Who sat down beside her'​.center(line_width))
puts(​'And scared her poor shoe dog away.'​.center(line_width))
Old Mother Hubbard
Sat in her cupboard
Eating her curds and whey,
When along came a spider
Who sat down beside her
And scared her poor shoe dog away.

Hmmm…I don’t think that’s how that nursery rhyme goes, but I’m too lazy to look it up. Speaking of laziness, see how I stored the width of the poem in the variable line_width? This was so that if I want to go back later and make the poem wider, I have to change only the first line of the program, instead of every line that does centering. With a very long poem, this could save me a lot of time. That’s the kind of laziness we want in our programs.

About that centering…you may have noticed that it isn’t quite as beautiful as a word processor would have done. If you really want perfect centering (and maybe a nicer font), then you should just use a word processor. Ruby is a wonderful tool, but no tool is the right tool for every job.

The other two string-formatting methods we’ll look at today are ljust and rjust, which stand for left justify and right justify. They are similar to center, except that they pad the string with spaces on the right and left sides, respectively. Let’s take a look at all three in action:

line_width = 40
str = ​'--> text <--'
puts(str.ljust( line_width))
puts(str.center(line_width))
puts(str.rjust( line_width))
puts(str.ljust(line_width/2) + str.rjust(line_width/2))
--> text <--
--> text <--
--> text <--
--> text <-- --> text <--
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.60.239