Multiple references in Ruby -


I expect the following code to print "8", "111" and "999". I used to think that each A, B, C, and D indicate the same memory location. If I change the location through one of them, then why would not the other change? Obviously, my argument is bad, or I ignore something instead "7", "7" and "8" prints

Why?

  a = b = c = d = 7b = 8 puts dc = 111 puts ad = 999 puts b  

[explanation]

/ Strong>

The reason for my illusion is that they change similar values, but I have suggested those results above. Are we talking about the same issue?

  a = b = c = d = 7 # a, b, c and d Indicates only for the integer object "7" b = 8 # b now indicates a new object "8" # "=" The value of the pointer integer does not change, # returns a new reference as above D appears in the line d # obviously, D still points to "7" C = 111 # C now indicates another integer object "111" a "still number" 7 "d = 999 # Ruby In, "integer" The object is irreversible so that you can not specify the integer in many contexts and change its value.  

As suggested tips have been suggested, you use an array to wrap the reference of your integer Because the array is unstable for you, then the value is able to change.

  a = b = c = d = [7] b [0] = 8 puts d [ 0] C [0] = 111 puts a [0] d [0] = 999 b [0]  

CL ARIFICATION:

If you come from a C ++ background, it may be strange because C ++ does two things with the same syntax, specifying the context and changing the value reference.

  int a = 10; // value 10 makes an int on the stack with EF & amp; amp; B = A; // Creates a reference for an int and gives a variable B = 5 references; Change the value in terms of // b (a) to 5 / a and b, values ​​are now placed in 5  

ruby, references are unstable and not integers (of course Opposite C ++). Therefore specifying the context will actually change the context and the referenced value will not be.

Another solution would be to create a class that is a floating integer:

  class MutableInteger attr_writer: value def initialize (value) @value = value end end of DEF value Value_i value end to def to_s value end end a = b = MutableInteger.new (10) a.value = 5 puts b # print 5  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -