I expected the following code to print “8”, “111” and “999”. I supposed that each a, b, c and d points to the same memory location. If I change the location through one of them, why would the other not to change? Clearly, my logic is poor, or I overlooked something. It prints “7”, “7” and “8”, instead.
Why?
a=b=c=d=7
b = 8
puts d
c = 111
puts a
d = 999
puts b
[Clarification]
The reason for my confusion is the example in the book (page 20). They change there similarly the values, but they get the results I suggested above. Are we speaking of the same issue?
in Ruby, the Integer object is immutable so you cannot assign an Integer to multiple reference and change its value after.
As @pts suggested, you should use an array to wrap your Integer reference because Arrays are mutable to you are able to change the value after.
CLARIFICATION:
If you come from a C++ background, it may be strange because C++ does 2 things with the same syntax, assigning the reference and changing the value referenced.
In Ruby, reference are mutable and integers are not (exactly the contrary to C++). So assigning a reference will actually change the reference and not the referenced value.
Another solution would be to create a class that is a mutable integer: