On Sat, Jan 14, 2012 at 3:38 PM, Ralph S. [email protected]
wrote:
a = “string”
b = “string”
causes three objects with different object id’s to be created.
It actually causes just two objects to be created.
irb(main):001:0> a = “string”
=> “string”
irb(main):002:0> b = “string”
=> “string”
irb(main):003:0> “string”.object_id
=> 19087248
This one is a new and different thing that is not related to your
above two lines of code at all.
irb(main):004:0> a.object_id
=> 21660552
irb(main):005:0> b.object_id
=> 22419972
I think what you are missing is that a literal String creates a new
string object. The fact that the characters are the same doesn’t mean
it’s the same object:
1.9.2p290 :001 > “string”.object_id
=> 14124100
1.9.2p290 :002 > “string”.object_id
=> 14101660
1.9.2p290 :003 > “string”.object_id
=> 14081660
1.9.2p290 :004 > “string”.object_id
=> 14068260
Yet
a = “string”
b = a
only causes two objects to be created.
It actually only causes one object to be created, see above.
irb(main):001:0> a = “string”
=> “string”
irb(main):002:0> b = a
=> “string”
irb(main):003:0> “string”.object_id
=> 22106544
irb(main):004:0> a.object_id
=> 22650984
irb(main):005:0> b.object_id
=> 22650984
A possible misunderstanding here would be to miss the difference
between an object and a variable. A variable is a reference to an
object. Several variables can reference the same object. Assigning
variables only changes what they reference, not the objects
themselves.
Yes, I know that one can do
a = “string”
b = a.clone
I understand what’s happening. I just don’t know why the language designer(s)
decided on – what is to me – surprising behavior.
I think that having objects be a separate concept from the variables
that reference them is pretty common, and provides very nice language
semantics.
Just think that a literal string is a new object every time it
appears, the same with hashes, for example.
So I have a Car Talk Puzzler (for which I do not have an answer): How would I
initialize a bunch of strings so that they are clones rather than the same object?
In other words how would I do the following which is invalid Ruby.
a = b.clone = c.clone = “How to clone?”
1.9.2p290 :005 > a = (b = (c = “How to clone?”).clone).clone
=> “How to clone?”
1.9.2p290 :006 > [a.object_id, b.object_id, c.object_id]
=> [14045460, 14045480, 14045520]
1.9.2p290 :007 > [a,b,c]
=> [“How to clone?”, “How to clone?”, “How to clone?”]
Jesus.