ruby variable as same object (pointers?)

前端 未结 7 989
-上瘾入骨i
-上瘾入骨i 2021-01-01 03:22
>> a = 5
=> 5
>> b = a
=> 5
>> b = 4
=> 4
>> a
=> 5

how can I set \'b\' to actually be \'a\' so that in the exa

7条回答
  •  -上瘾入骨i
    2021-01-01 03:33

    You can't. Variables hold references to values, not references to other variables.

    Here's what your example code is doing:

    a = 5 # Assign the value 5 to the variable named "a".
    b = a # Assign the value in the variable "a" (5) to the variable "b".
    b = 4 # Assign the value 4 to the variable named "b".
    a # Retrieve the value stored in the variable named "a" (5).
    

    See this article for a more in-depth discussion of the topic: pass by reference or pass by value.

提交回复
热议问题