From: Brian Candler Date: 2009-04-30T19:30:33+09:00 Subject: Re: Random Access using IO#pos in code blocks Robert Klemme wrote: > I do have to admit though that I > do not know when the object is allocated (i.e. at time of match or > when referencing $`). Experiment suggests the MatchData is created immediately on the match, and the string is instantiated lazily from that. This makes sense; it would be very inefficient to allocate strings for $`, $1, $2, $3, ... $' when maybe none of them will be used. But the MatchData object has the original string plus all the offsets. def count(klass) c = 0 ObjectSpace.each_object(klass) { c += 1 } c end str = " foo bar baz " c1 = [count(MatchData), count(String)] str =~ /(\w+)/ c2 = [count(MatchData), count(String)] x = $~ c3 = [count(MatchData), count(String)] y = $` c4 = [count(MatchData), count(String)] puts [c1,c2,c3,c4].inspect # [[0, 188], [1, 188], [1, 188], [1, 189]] -- Posted via http://www.ruby-forum.com/.