From: Pete Yandell Date: 2007-07-20T13:57:18+09:00 Subject: Re: Is there a replacement for sub? 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. a.sub! returns nil if no matches are found. You want either: a = a.sub(' ', '') or a.sub!(' ', '') And try using times rather than a for loop and a useless variable: 3.times { a.sub!(' ', '') } You could also replace the whole thing with: "a b c d e f".split(' ', 4).join Pete Yandell http://notahat.com/