From: Gavin Kistner Date: 2005-09-26T07:10:52+09:00 Subject: Re: String#ggsub On Sep 25, 2005, at 3:33 PM, Logan Capaldo wrote: >> I occasionally find myself with gsub regexp that either eat too >> much, or work within a nesting, such that I need to run gsub more >> than once in order to get the desired end result. The code I end >> up writing tends to be of the form: >> >> while foo.gsub!( /.../, ... ); end > > I'm kinda curious, can we see an example of a regex where this was > necessary? Here's a pared-down example from this week's ruby quiz: class Array; def random; self[ rand( self.length ) ]; end; end class String def variation out = self.dup while out.gsub!( /\(([^())?]+)\)(\?)?/ ){ ( $2 && ( rand > 0.5 ) ) ? '' : $1.split( '|' ).random }; end out end end q = "(How (much|many)|What) is (the (value|result) of)? 10 + 2?" 10.times{ puts q.variation } #=> What is the value of 10 + 2? #=> What is the value of 10 + 2? #=> How many is 10 + 2? #=> What is 10 + 2? #=> What is 10 + 2? #=> How many is 10 + 2? #=> What is the value of 10 + 2? #=> What is 10 + 2? #=> What is the result of 10 + 2? #=> What is the result of 10 + 2?