From: "Peña, Botp" Date: 2007-07-20T18:12:26+09:00 Subject: Re: Is there a replacement for sub? From: Michael W. Ryder [mailto:_mwryder@worldnet.att.net] # a = "a b c d e f" # for i in 1..3 # a = a.sub!(' ', '') ^^^^^ lose that # 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!(' ', '') ^^^^^ same. lose it. # end # puts a ==> returns error.rb:3: private method `sub!' called for # nil:NilClass (NoMethodError, and a is now nil. a.sub! will modify a. so, do NOT use a=a.sub!, it's NOT right. just use plain a.sub!. ruby has already simplified it, do not make it simpler :) eg, C:\family\ruby>cat -n test.rb 1 puts "---test 3 subs using for---" 2 a = "a b c d e f" 3 for i in 1..3 4 a.sub!(' ', '') 5 end 6 puts a 7 8 puts "---test 10 subs using for---" 9 a = "a b c d e f" 10 for i in 1..10 11 a.sub!(' ', '') 12 end 13 puts a 14 15 16 puts "---test 3 subs using times---" 17 a = "a b c d e f" 18 3.times do 19 a.sub!(' ', '') 20 end 21 puts a 22 23 24 puts "---test 10 subs using times---" 25 a = "a b c d e f" 26 10.times do 27 a.sub!(' ', '') 28 end 29 puts a C:\family\ruby>ruby test.rb ---test 3 subs using for--- abcd e f ---test 10 subs using for--- abcdef ---test 3 subs using times--- abcd e f ---test 10 subs using times--- abcdef C:\family\ruby> is that clear enough? kind regards -botp