From: David Alan Black Date: 2002-01-12T04:07:58+09:00 Subject: RE: gsub: arrays as parameters Hi -- On Sat, 12 Jan 2002, Jack Dempsey wrote: > 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 I *knew* I wasn't looking at it closely enough :-) I missed the point that both args were arrays. Hmmm... you could do: str = "Hello, I am a string" pats = [/ll/, /am/] subs = ['LL', 'AM'] subs.each_index {|i| str.gsub!(pats[i], subs[i])} which is fairly compact. Then again, I don't see any reason not to write this as a String method. Personally I don't think I'd advocate changing #gsub to behave this way, though, partly based on the theory that once you go down that path, it's hard to know where to stop. (Should it also take hashes, with regexes as keys and replacement strings as values?) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav