From: Jack Dempsey Date: 2002-01-12T03:56:15+09:00 Subject: RE: gsub: arrays as parameters Hi David, Thanks for the advice! I believe the idea is a good one (pretty much stolen from PHP), although my code looks like it needs some tuning... The idea is this: Often I will want to do many regex substitutions: different patterns with different replacements. Now, perhaps I'm missing some cool Ruby trick, but I'd like to be able to do this: patterns = [/abc/,/def/] subs = ['ABC','DEF'] gsub!(patterns,subs) etc, I think you get the idea, and I don't know how else I would do it without stacking gsubs...i'm sure there are other ways, but I just wanted to see if there was any reason that gsub can't take arrays as parameters And for the dup trick, thanks! I knew there must have been a simpler way... Jack "On two occasions I have been asked [by members of Parliament], 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. --Charles Babbage" -----Original Message----- From: David Alan Black [mailto:dblack@candle.superlink.net] Sent: Friday, January 11, 2002 1:40 PM To: ruby-talk ML Subject: Re: gsub: arrays as parameters Hello -- On Sat, 12 Jan 2002, Jack Dempsey wrote: > I wrote this and it works well for me. I wanted to see what others > thought, and ask if anyone (Matz?) knows the pros and cons of making a > change like this to gsub. It looks more like a new, different method (where the first argument has to respond to each_with_index, which Regexp objects don't), rather than a modification of gsub(!). > > class String > def gsubx!(regex,replace) > regex.each_with_index do |x,i| > self.gsub!(x,replace[i]) > end > end > > def gsubx(regex,replace) > str = self.dup > regex.each_with_index do |x,i| > str.gsub!(x,replace[i]) > end > str > end Couldn't that be: def gsubx(*args) dup.gsubx!(*args) end > end You've eliminated the block form -- i.e., your gsubx(!) doesn't take a block, which gsub(!) does. Also, I'm not exactly sure what this gains you, over using a pattern with '|' in it. I probably haven't puzzled through it enough. Can you give an example? David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav