From: Robert Klemme Date: 2005-11-09T07:42:12+09:00 Subject: Re: gsub and gsub! are inconsistent aurelianito wrote: > Hi all! > > I've been trying to optimize the code > a_string.gsub(/pattern_1/, "REPLACE_1").gsub(/pattern_2/, > "REPLACE_2").gsub(/PATTERN_3/,"REPLACE_3"). > > with a_string.gsub(/pattern_1/, "REPLACE_1").gsub!(/pattern_2/, > "REPLACE_2").gsub!(/pattern_3/,"REPLACE_3") (note the '!' on the > second and third gsub). > > IMHO, this two blocks of pseudocode should behave in the same way, but > if the second pattern don't matches, it returns null on the second > version, and then generates an exception. > Why is it than the destructive gsub behaves differently? To be able to determine whether something was changed if s.gsub!(...) puts "oops, changed!" end > Do you think that the current behaviour is the right behaviour? Why? If there were no other reasons then at least existing code. But there are other reasons (see above). Btw, did you consider changing your code altoghether? Depending on your patterns and replacements, there are other options possible: s.gsub!(/pat1|pat2/) {|m| replacements[m]} s.gsub! /(pat1)|(pat2)/ do |m| case when m[1]; "re1" when m[2]; "re2" else raise "Unexpected" end end Kind regards robert