From: Robert Dober Date: 2008-06-16T20:53:01+09:00 Subject: Re: how to stop gsub from returning nil On Mon, Jun 16, 2008 at 12:39 PM, Tom Cloyd wrote: > Robert Dober wrote: >> >> On Mon, Jun 16, 2008 at 9:58 AM, Tom Cloyd wrote: >> >>> >>> I'm trying to use gsub to do a number of transformations in an array of >>> strings. I find that when a particular transformation does NOT happen, >>> because the searched-for substring is not there, gsub returns nil. This >>> effectively ruins my output. I don't want nothing. I want the string >>> that's >>> being processed, returned with or without any transformations. Is there >>> any >>> alternative to testing for a return of nil before calling gsub, so as to >>> avoid the wiping out of my string? I've looked for something to use other >>> than String::gsub, and have not found anything. >>> >>> Code: >>> >>> filein = open( "{whatever}" ) >>> fi = filein.readlines >>> delta = [ ["

", ''], ["", ''] ] >>> results = fi.collect do |x| >>> delta.each do |y| >>> debugger x.gsub!(y[0], y[1]) >>> end >>> end >>> >>> t. >>> >>> -- >>> >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> Tom Cloyd, MS MA, LMHC >>> Private practice Psychotherapist >>> Bellingham, Washington, U.S.A: (360) 920-1226 >>> << tc@tomcloyd.com >> (email) >>> << TomCloyd.com >> (website & psychotherapy weblog) >>> << sleightmind.wordpress.com >> (mental health issues weblog) >>> << directpathdesign.com >> (web site design & consultation) >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> >>> >>> >>> >> >> >> >> Why not write a simple wrapper? >> >> Ruby 1.9 >> class String >> def mysub! *args, &blk >> tap{ gsub!( *args, &blk ) } >> end >> end >> >> Ruby 1.8 or 1.9 too ;) >> ... >> def mysub!... >> gsub!.... >> self >> end >> >> >> Cheers >> Robert >> > > Simple answer: I don't know the idiom. wrapper means the same as with candy, leave gsub! to do the task and wrap mysub! around to return self as gsub! does not. The first idiom is from RUby1.9 I 'll give you the simple example again, it is easier to understand class String def mysub! *args, &blk gsub! *args, &blk # we still want the basic gsub! behavior, so we just let it do its work! self # aditionally we return the (potentially modified) string you were missing so badly ;) end end Quite simple, no? If not Albert will not be happy ;). HTH Robert -- http://ruby-smalltalk.blogspot.com/ --- As simple as possible, but not simpler. Albert Einstein