From: Brian Candler Date: 2008-09-19T04:17:15+09:00 Subject: Re: why one array continues to grow after repeated call Oh I forgot to add - while playing about with this in irb, the method "object_id" is really useful. It returns the actual pointer. (Well, it's not *exactly* the pointer; it's a pointer which has been cleverly encoded to include some information about the type of the object, to optimise some common operations, but internally Ruby is able to map the object_id to the actual memory location with some simple bit-masking) irb(main):001:0> a = "hello" => "hello" irb(main):002:0> b = a => "hello" irb(main):003:0> a.object_id => -605500598 irb(main):004:0> b.object_id => -605500598 irb(main):005:0> a << " world" => "hello world" irb(main):006:0> a => "hello world" irb(main):007:0> b => "hello world" Here, you can see that a and b really are pointers to the same object. You could have done `b << " world"` instead of `a << " world"` and got exactly the same effect. In both cases you are invoking method "<<" with argument " world" on the object at "memory location"(ish) -605500598. Contrast with: irb(main):008:0> a = "hello" => "hello" irb(main):009:0> b = "hello" => "hello" irb(main):010:0> a.object_id => -605560548 irb(main):011:0> b.object_id => -605574918 irb(main):012:0> a << " world" => "hello world" irb(main):013:0> a => "hello world" irb(main):014:0> b => "hello" You can see clearly that a and b point to different strings, which happen to start out with the same content. Incidentally, if a points to a string and you want b to point to a different string with the same content, you can do b = a.dup or b = String.new(a) This creates a new String object, and copies the content byte by byte from the old one into the new one, leaving b pointing at the new one. In practice this doesn't need to be done very much. Finally, note that if you write a += " world" this is short for a = a + " world" Now the expression on the RHS creates a new string object, being the concatenation of the original string and " world", and then this pointer is stored in a; a no longer points to what it did before. But assigning to a doesn't affect any other local variable which points to the original string. So: irb(main):018:0> a = "hello" => "hello" irb(main):019:0> b = a => "hello" irb(main):020:0> a.object_id => -605642908 irb(main):021:0> b.object_id => -605642908 irb(main):022:0> a += " world" => "hello world" irb(main):023:0> a.object_id => -605661638 irb(main):024:0> b.object_id => -605642908 irb(main):025:0> a => "hello world" irb(main):026:0> b => "hello" You can see that a is pointing to a new object, whereas b is still pointing to the original one. I hope this makes things clearer rather than muddier :-) Regards, Brian. -- Posted via http://www.ruby-forum.com/.