From: x17y19 Date: 2008-04-12T03:15:04+09:00 Subject: Re: surprise in sub On Apr 11, 9:15 am, m...@tidbits.com (matt neuburg) wrote: > irb(main):001:0> s = "\\\\" > => "\\\\" > irb(main):002:0> s.length > => 2 > irb(main):003:0> s = "howdy".sub("howdy", s) > => "\\" > irb(main):004:0> s.length > => 1 > > So merely using a string as the second param of sub (the replacement > value) can cause that string to be altered. > > Now, the documentation does "warn" that sequences \1, \2 etc. are valid > in the replacement string. This suggests that the replacement string is > processed before use; to be sure, it says nothing about "\\" explicitly, > but I do see of course that one must deal with "\\" in order to escape > the escaping. Furthermore, there's a "workaround", namely to write the > third line as follows: > > s = "howdy".sub("howdy") {|x| s} > > Still, I got seriously caught by this behavior and it was tricky to > track down. m. > > -- > matt neuburg, phd = m...@tidbits.com,http://www.tidbits.com/matt/ > Leopard -http://www.takecontrolbooks.com/leopard-customizing.html > AppleScript -http://www.amazon.com/gp/product/0596102119 > Read TidBITS! It's free and smart.http://www.tidbits.com s is changing because you assigned to it, not because of using it as the second parameter of sub(). Try assigning the result to a different variable like so: ss = "howdy".sub("howdy", s)