Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!talisker.lacave.net!lacave.net!not-for-mail From: Joel VanderWerf Newsgroups: comp.lang.ruby Subject: Re: Replace any multiple whitespaces with single white space Date: Mon, 25 Apr 2011 14:14:46 -0500 Organization: Service de news de lacave.net Lines: 40 Message-ID: <4DB5C81E.1080000@gmail.com> References: <4DB5C2CA.3070705@gmail.com> NNTP-Posting-Host: bristol.highgroove.com Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: talisker.lacave.net 1303758909 93301 65.111.164.187 (25 Apr 2011 19:15:09 GMT) X-Complaints-To: abuse@lacave.net NNTP-Posting-Date: Mon, 25 Apr 2011 19:15:09 +0000 (UTC) In-Reply-To: X-Received-From: This message has been automatically forwarded from the ruby-talk mailing list by a gateway at comp.lang.ruby. If it is SPAM, it did not originate at comp.lang.ruby. Please report the original sender, and not us. Thanks! For more details about this gateway, please visit: http://blog.grayproductions.net/categories/the_gateway X-Mail-Count: 382161 X-Ml-Name: ruby-talk X-Rubymirror: Yes X-Ruby-Talk: <4DB5C81E.1080000@gmail.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.ruby:3474 On 04/25/2011 12:02 PM, Josh Cheek wrote: > On Mon, Apr 25, 2011 at 1:51 PM, Joel VanderWerf > wrote: > >> On 04/25/2011 11:44 AM, Michelle Pace wrote: >> >>> Hello, I need to make the first string below into the second string. >>> That is, only single white spaces are permitted. >>> >>> "1/4 WELDING LEVER FRONT DRW 14844-C MAT WMA1CM-WLFRONT" >>> into >>> "1/4 WELDING LEVER FRONT DRW 14844-C MAT WMA1CM-WLFRONT" >>> >>> >>> >>> I want to use the sub! method. Why does the below code not work? Is my >>> pattern incorrect? >>> >>> descrip = "1/4 WELDING LEVER FRONT DRW 14844-C MAT WMA1CM-WLFRONT" >>> descrip.sub!(/\s+/,' ') >>> puts descrip >>> >> >> sub! only affects the *first* match. You can substitute globally with gsub. >> Also you might as well only match 2 or more spaces: >> >> descrip.gsub!(/\s\s+/,' ') >> >> > > I think the original regex is better, because leads to more consistent > results: > > "hello\tworld !".gsub(/\s\s+/,' ') # => "hello\tworld !" > "hello\tworld !".gsub(/\s+/,' ') # => "hello world !" > Good point, but it depends on what you're trying to be consistent with. Maybe the goal is to squeeze space, but preserve tab layout for readability.