I am studying object_id method behavior in Ruby in order to know when a new object is created. I can understand (1) is identical to (2) and (3) is identical to (4). But I do not understand why (5) is not identical to (6).
(1) upto (6) are described below with my source code.
So I would like to understand when object_id will be changed (newly assigned) in Ruby. Does anybody explain it concisely?
Thank you very much in advance.
source code
a = "foo"
b = a
b.slice!(0)
p a.object_id # (1)
p b.object_id # (2)
b = b
p a.object_id # (3)
p b.object_id # (4)
b = b.slice(0)
p a.object_id # (5)
p b.object_id # (6)
result
70302398954840
70302398954840
70302398954840
70302398954840
70302398954840
70302398954680
Variables are not objects and mutating an object does not change what the object is. That is, mutating an object will never change which variables evaluate to that object.
The difference between the two methods is that
slice!mutates the original string/object (ick!) andslicereturns a new string/object without mutating the original (yay!).In the following
Xdenotes a particular (but arbitrary) string, andYrepresents a different particular (but arbitrary) string. Do not confuseXandYwith variables; they merely represent different objects to explain the behavior.