Iterating and Incrementing Strings in Ruby - Managing Whitespace, etc. (Page 3 of 6 )
You can adjust whitespace (or other characters) on the left or right of a string, center a string in whitespace (or other characters), and strip whitespace away using the following methods. First, create a string—the title of a Shakespeare play:
title = "Love's Labours Lost"
How long is the string? This will be important to you (lengthandsizeare synonyms).
title.size # => 19
The stringtitleis 19 characters long. With that information in tow, we can start making some changes. Theljustandrjustmethods pad a string with whitespace or, if specified, some other character. The string will be right justified, and the number of characters, whitespace or otherwise, must be greater than the length of the string. Make sense? I hope so. Let’s go over an example or two.
Let’s call these two methods with an argument (an integer) that is less than or equal to the length of the string.
What happened? Nothing! That’s because the argument must be greater than the length of the string in order to do anything. The added whitespace is calculated based on the length of the string plus the value of the argument. Watch:
See how it works now? In the call toljust, one space character is added on the right (20 – 19 = 1), and the call torjustadds six characters to the left (25 – 19 = 6). If it seems backward, just remember that the string is always right justified. Still confused? So am I, but we’ll go on. You can use another character besides the default space character if you’d like:
We’ve been adding whitespace and other characters. What if you just want to get rid of it? Uselstrip,rstrip, andstrip(lstrip!,rstrip!, andstrip!). Suppose you have a string surrounded by whitespace:
fear = " Fear is the little darkroom where negatives develope. --Michael Pritchard "
Oops. Fell asleep with my thumb on the space bar—twice! I can fix it easily now, starting with the left side (make the change stick to the original string withlstrip!):
fear.lstrip! # => "Fear is the little darkroom where negatives develope. -- Michael Pritchard "
Now the right side:
fear.rstrip! # => "Fear is the little darkroom where negatives develope. -- Michael Pritchard"
Or do the whole thing at once:
fear.strip! # => "Fear is the little darkroom where negatives develope. -- Michael Pritchard"
strip removes other kinds of whitespace, too:
"\t\tBye, tabs and line endings!\r\n".strip # => "Bye, tabs and line endings!"