From: "Michael W. Ryder" <_mwryder@...> Date: 2007-07-20T17:44:58+09:00 Subject: Re: Is there a replacement for sub? Robert Klemme wrote: > 2007/7/20, Michael W. Ryder <_mwryder@worldnet.att.net>: >> Chris Shea wrote: >> > On Jul 19, 8:59 pm, "Michael W. Ryder" <_mwry...@worldnet.att.net> >> > wrote: >> >> I was trying to come up with a way to remove x instances of a >> character >> >> from a string and came up with a problem. If I enter: >> >> >> >> a = "a b c d e f" >> >> for i in 1..3 >> >> a = a.sub!(' ', '') >> >> end >> >> puts a ==> returns 'abcd e f' which is correct. >> >> >> >> But if I enter: >> >> >> >> a = "a b c d e f" >> >> for i in 1..10 >> >> a = a.sub!(' ', '') >> >> end >> >> puts a ==> returns error.rb:3: private method `sub!' called for >> >> nil:NilClass (NoMethodError, and a is now nil. >> >> >> >> What I am looking for is a way to remove the first n instances of a >> >> blank from the string without wiping out the string if it does not >> >> contain at least n blanks. I assume there is a way to do this with >> >> regular expressions, but have not found it yet. This is something an >> >> editor I liked, UCEDIT, on the CDC Cyber had in the 70's. >> > >> > sub! modifies the string in place, so you don't need to say a = a.sub! >> > (' ',''). a is already changing. And since sub! is modifying in >> > place, it returns nil if no changes are being made, and you end up >> > setting a to nil when that happens. >> > >> > a = 'a b c d e f' >> > 10.times { a.sub!(' ','')} >> > puts a # 'abcdef' >> > >> > HTH, >> > Chris >> > >> >> I think this is where I am having problems understanding Ruby. I have >> to use a.sub(' ', '') in a for loop but use a.sub!(' ', '') when using a >> times loop. Why the difference? > > There is none. a.sub! is an alternative to a = a.sub - wherever you use > it. > Except where you use b = a.sub!(' ', ''). Then if you loop through this statement 10 times b is nil, not the abcdef I expected. This is what is so confusing. At the same time I can not use b = a.sub(' ', '') as it always returns ab c d e f regardless of how many times I execute it, which is what I would expect. So, how would I do this? 10.times { b = a.sub!(' ', '')} doesn't work, it errors out. b = a.split(' ', 10).join works for this contrived example but I am not sure if it would work for something like replacing the first 12 occurrences of \","\ with \\t\. > robert >