Comparing and Manipulating Strings in Ruby - The chomp and chop Methods
(Page 3 of 4 )
The chop (or chop!) method chops off the last character of a string, and thechomp(chomp!) method chomps off the record separator ($/)—usually just a newline—from a string. Consider the stringjoe, a limerick created as a here document:
joe = <<limerick
There once was a fellow named Joe
quite fond of Edgar Allen Poe
He read with delight
Nearly half the night
When his wife said "Get up!" he said "No."
limerick # => "There once was a fellow named Joe\nquite fond of Edgar Allen Poe\n
He read with delight\n Nearly half the night\nWhen his wife said "Get up!" he
said "No."\n"
Applychomp!to remove the last record separator (\n):
joe.chomp! # => "There once was a fellow named Joe\nquite fond of Edgar Allen Poe\n
He read with delight\n Nearly half the night\nWhen his wife said "Get up!" he said "No.""
Now apply it again, andchomp!returnsnilwithout altering the string because there is no record separator at the end of the string:
joe.chomp! # => nil
chop,chomp’s greedy twin, shows no mercy on the string, removing the last character (a quote) with abandon:
joe.chop! = "There once was a fellow named Joe\nquite fond of Edgar Allen Poe\n He
read with delight\n Nearly half the night\nWhen his wife said "Get up!" he said \
"No"
Next: The delete Method >>
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.
|
|