Iterating and Incrementing Strings in Ruby
(Page 1 of 6 )
In this conclusion to a three-part series focusing on strings in Ruby, you will learn not only how to iterate over and increment a string, but how to manage whitespace, convert a string, and more. It is excerpted from chapter four of
Learning Ruby, written by Michael Fitzgerald (O'Reilly; ISBN: 0596529864). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
From a String to an Array
Conveniently, split converts a string to an array. The first call to splitis without an argument:
"0123456789".split # => ["0123456789"]
That was easy, but what about splitting up all the individual values and converting them into elements? Do that with a regular expression (//) that cuts up the original string at the junction of characters.
"0123456789".split( // ) # => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
In the next example, the regular expression matches a comma and a space (/, /):
c_w = "George Jones, Conway Twitty, Lefty Frizzell, Ferlin Husky"
# => "George Jones, Conway Twitty, Lefty Frizzell, Ferlin Husky"
c_w.split(/, /) # => ["George Jones", "Conway Twitty", "Lefty Frizzell", "Ferlin
Husky"]
Case Conversion
You can capitalize a word, sentence, or phrase with capitalize or capitalize!. (By now you should know the difference between the two.) Here is a pair of sentences that are under the influence of capitalize:
"Ruby finally has a killer app. It's Ruby on Rails.".capitalize # => "Ruby finally
has a killer app. it's ruby on rails."
Notice that the second sentence is not capitalized, which doesn’t look so good. Now you can see thatcapitalizeonly capitalizes the first letter of the string, not the beginning of succeeding sentences. Plan accordingly.
Next: Iterating Over a String >>
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.
|
|