Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>a=b=c=d=7 # a, b, c and d points to the same integer object "7" b = 8 # b now points to a new object "8" # "=" does not change the value of the pointer integer, # it assings a new reference like in the line above puts d # obviously, d still points to "7" c = 111 # c now points to another integer object "111" puts a # a still points to "7" d = 999 # d now points to a new integer object "999" puts b # b still points to "8" </code></pre> <p>in Ruby, the Integer object is immutable so you cannot assign an Integer to multiple reference and change its value after. </p> <p>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.</p> <pre><code>a=b=c=d=[7] b[0] = 8 puts d[0] c[0] = 111 puts a[0] d[0] = 999 puts b[0] </code></pre> <p>CLARIFICATION:</p> <p>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.</p> <pre><code>int a = 10; // creates an int on the stack with value 10 int&amp; b = a; // creates a reference to an int and references the a variable b = 5; // change the value referenced by b (so a) to 5 // a and b now hold the value 5 </code></pre> <p>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.</p> <p>Another solution would be to create a class that is a mutable integer:</p> <pre><code>class MutableInteger attr_writer :value def initialize(value) @value = value end def inspect value end def to_i value end def to_s value end end a = b = MutableInteger.new(10) a.value = 5 puts b # prints 5 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload