Brian Candler
5/3/2007 7:41:00 AM
On Thu, May 03, 2007 at 01:30:06PM +0900, Michael W. Ryder wrote:
> Is there a way to denote a null in the replacement for a character using
> this method? For example, if I have a = "Jones,Ja'me" and I want to
> convert the comma to a space and remove the apostrophe without placing a
> character in there. I know I can use a.tr(",", " ").tr("'", "") to get
> the desired result but would prefer to be able to say something like
> a.tr(",'", " ") and have it remove the apostrophe and replace the comma
> in one step. Besides, if I am going to be removing a lot of punctuation
> the string could get very long and complicated.
Removing the apostrophe, and replacing it with null, are two different
things. But you could use the null as a placeholder and then remove it
afterwards:
a = "Jones,Ja'me"
a.tr(",'"," \000").delete("\000")
No matter how much punctuation you want to remove, it's still only two
steps.
If you want this in a single step, hmm, how about:
REPLACE = {
"," => " ",
"'" => "",
}
REPLACE_RE = /#{REPLACE.keys.map {|k| Regexp.escape(k) }.join("|")}/
a.gsub(REPLACE_RE) { |m| REPLACE[m] }
It might look a bit long-winded, but the constant initialisation only has to
be done once at the top of your program, and it can replace arbitary
sequences of characters with other arbitary sequences.
HTH,
Brian.