From: Mark Sparshatt Date: 2004-06-23T05:03:38+09:00 Subject: Re: Newbie question - how to replace multiple whitespace within astring? Brian Tully wrote: >on 6/22/04 3:36 PM, Joel VanderWerf at vjoel@PATH.Berkeley.EDU wrote: > > > >>Brian Tully wrote: >> >> >> >>>Should I use state.squeeze(" ") to ensure that it always returns the state >>>even if nothing was changed? squeeze! seems to return nil if nothing needs >>>to be changed. >>> >>> >>str.squeeze! is destructive (changes the String object referred to by >>str), and str.squeeze is not. So it just depends on whether you need to >>keep the original string intact (I'd guess not). >> >> > > >Hmmm I'm a little hazy... > >I want Ruby to strip out any instances of multiple whitespace and return the >"correct" string. I also want it to return the string regardless of whether >the squeeze function modified it. > >So in these examples I would hope for the following: > > @state = @user['state'].squeeze(" ") > >if @user['state'] was originally "New York" I would hope that the above >would set @state to "New York". > >In addition if @user['state'] was originally "California" I would hope that >the above would still set @state to "California". > > > > this is correct @user["state"] = "New york" @state = @user["state"].squeeze p @state #=> "New york" @user["state"] = "California" @state = @user["state"].squeeze p @state #=> "California" >squeeze! - Squeezes str in place, returning either str, or nil if no >changes were made. > >I interpret this as if no changes were made "nil" will be returned, so in my >example of "California" wouldn't this set @state to nil? > > > correct you would use squeeze if you wanted to modify @user["state"]. In which case the following lines are about equivilent @user["state"] = @user["state"].squeeze @user["state"].squeeze! -- Mark Sparshatt