From: why the lucky stiff Date: 2002-12-11T14:58:28+09:00 Subject: Re: replacing chars in string Shashank Date (sdate@kc.rr.com) wrote: > I am trying to globally replace characters in a string by "chaining" the > String#gsub method like so: > > str = "count=(a+b); if(a<=b) d[i]=10;f(a,b)" > puts str.gsub(/,/,' , ').gsub(/\(/,' ( ').gsub(/\)/,' ) > ').gsub(/([^<>])=/,'\1 = ').gsub(/;/,";\n") > > Is there a better (faster) way to do this ? For your need, the chained gsub is the fasted I can think of. Here's my comparison against two solutions involving the block form of gsub. I'm using ruby 1.7.3 (2002-11-27) [i586-linux]. require 'benchmark' include Benchmark n = 1000 str = "count=(a+b); if(a<=b) d[i]=10;f(a,b)" test = nil bm do |x| x.report( "chained gsubs:" ) do n.times do test = str.gsub(/,/,' , ').gsub(/\(/,' ( ').gsub(/\)/,' ) ').gsub(/([^<>])=/,'\1 = ').gsub(/;/,";\n") end # puts # p test end x.report( "grouped gsub:" ) do n.times do test = str.gsub( /(?:(,|\(|\)|[^<>]=)|(;))/ ) do if $1 "#{ $1[0..-2] } #{ $1[-1,1] } " else "#{ $2 }\n" end end end # puts # p test end x.report( "gsub and case:" ) do n.times do test = str.gsub( /[,();]|[^<>]=/ ) do |m| case m when /=$/ "#{ $` } = " when /;/ ";\n" else " #{ m } " end end end # puts # p test end end Benchmark results: user system total real chained gsubs: 0.830000 0.000000 0.830000 ( 0.831508) grouped gsub: 2.020000 0.000000 2.020000 ( 2.022475) gsub and case: 1.270000 0.000000 1.270000 ( 1.277238) _why