From: Mike Steiner Date: 2007-05-31T03:06:06+09:00 Subject: Re: are MatchData objects mutable? ------=_Part_4854_16121919.1180548365607 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Sorry, but now I'm completely confused. Arrays don't have a .sub! method, and m[1] is a string. And I can reference m[1], m[2], etc. in any order and get the same strings each time. Why are the object id's of m[1] different each time you reference it (in your example)? Mike Steiner On 5/26/07, dblack@wobblini.net wrote: > > Hi -- > > On Sun, 27 May 2007, Mike Steiner wrote: > > > A few times in my programs I've tried to modify elements of the array > > returned by .match, and it always causes strange errors later in my > code. > > > > For example, if I do: > > > > s = "aaa bbb ccc" > > m = /(.*) (.*) (.*)/.match(s) > > m[1].sub! ( "aa" , "" ) > > > > I get strange results, but if I instead do: > > > > s = "aaa bbb ccc" > > m = /(.*) (.*) (.*)/.match(s) > > x = m[1].dup > > x.sub! ( "aa" , "" ) > > > > it works fine. What's going on? > > Looking at the source (fairly quickly, but I think this is what's > happening), it looks like m[1] calls match_aref, which calls > rb_reg_nth_match, which hands back a different string object each > time. So doing a sub! on it doesn't have any impact on the string you > get the next time you do the [1] operation. > > You can also see this like this, where each [1] string is a different > object: > > irb(main):006:0> m = /(abc)/.match("abc") > => # > irb(main):007:0> m[1].object_id > => 1713410 > irb(main):008:0> m[1].object_id > => 1698110 > irb(main):009:0> m[1].object_id > => 1684420 > > etc. > > > David > > -- > Q. What is THE Ruby book for Rails developers? > A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) > (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) > Q. Where can I get Ruby/Rails on-site training, consulting, coaching? > A. Ruby Power and Light, LLC (http://www.rubypal.com) > > ------=_Part_4854_16121919.1180548365607--