Comparing and Manipulating Strings in Ruby - Manipulating Strings
(Page 2 of 4 )
Here’s a fun one to get started with. The * method repeats a string by an integer factor:
"A horse! " * 2 # => "A horse! A horse! "
You can concatenate a string to the result:
taf = "That's ".downcase * 3 + "all folks!" # => "that's that's that's all folks!"
taf.capitalize # => "That's that's that's all folks!"
Inserting a String in a String
The insert method lets you insert another string at a given index in a string. For example, you can correct spelling:
"Be carful.".insert 6, "e" # => "Be careful."
or add a word (plus a space):
"Be careful!".insert 3, "very " # => "Be very careful!"
or even throw the*method in just to prove that you can:
"Be careful!".insert 3, "very " * 5 # => "Be very very very very very careful!"
Changing All or Part of a String
You can alter all or part of a string, in place, with the
[]= method. (Like[], which is the counterpart ofslice,[]=is an alias ofslice!, so anywhere you use[]=, you can useslice!, with the same arguments.)
Given the following strings (some scoundrel has been editing our Shakespeare text):
line = "A Porsche! a Porsche! my kingdom for a Porsche!"
cite = "Act V, Scene V"
speaker = "King Richard, 2007"
enter a string as the argument to[]=, and it will return the new, corrected string, if found;nilotherwise.
speaker[", 2007"]= "III" # => "III"
p speaker # => "King Richard III"
That’s looking better.
If you specify aFixnum(integer) as an index, it returns the corrected string you placed at the index location. (String lengths are automatically adjusted by Ruby if the replacement string is a different length than the original.)
cite[13]= "IV" # => "IV"
p cite # => "Act V, Scene IV"
At the index13,[]=found the substringVand replaced it withIV.
You can use an offset and length (twoFixnums) to tell[]=the index of the substring where you want to start, and then how many characters you want to retrieve:
line[39,8]= "Porsche 911 Turbo!" # => "Porsche 911 Turbo!"
p line # => "A Porsche! a Porsche! my kingdom for a Porsche 911 Turbo!"
You started at index39, and went8characters from there (inclusive).
You can also enter a range to indicate a range of characters you want to change. Include the last character with two dots (..):
speaker[13..15]= "the Third" # => "the Third"
p speaker # => "King Richard the Third"
You can also use regular expressions (see “Regular Expressions,” later in this chapter), as shown here:
line[/Porsche!$/]= "Targa!" # => "Targa!"
p line # => "A Porsche! a Porsche! my kingdom for a Targa!"
The regular expression/Porsche!$/ matches ifPorsche!appears at the end of the line ($). If this is true, the call to[]=exchangesPorsche!withTarga!.
Next: The chomp and chop Methods >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|