From: Ken Bloom Date: 2007-07-20T20:40:00+09:00 Subject: Re: Is there a replacement for sub? On Fri, 20 Jul 2007 02:59:35 +0000, Michael W. Ryder 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. a.sub! modifies the string in place, changing only the first occurance. if it finds something, it returns self, if it finds nothing, it returns nil (so you can find out whether it changed anything.) So there's no need to do the a=a.sub!. Just use a.sub! on its own. a.sum (without the!) always returns a string, whether something was found or not (in which case it returns the unmodified string), and never modifies the string itself -- it always returns a copy. gsub! and gsub work similarly, but they change all matching strings in one fell swoop. (The g in the name is a holdover from standard UNIX utilities such as sed, ex, and vi that use the letter g as a modifier to mean "replace all matches") --Ken -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/