0
在這個紅寶石1.9.2代碼:爲什麼這個Proc的變量引用的對象改變了?
class ExampleClass
def self.string_expander(str)
-> do
p "start of Proc. str.object_id is #{str.object_id}"
str *= 2
p "end of Proc. str.object_id is #{str.object_id}"
end
end
end
string = 'cat' # => "cat"
p "string.object_id is #{string.object_id}" # => "string.object_id is 70239371964380"
proc = ExampleClass.string_expander(string) # => #<Proc:[email protected](irb):3 (lambda)>
proc.call
# "start of Proc. str.object_id is 70239371964380"
# "end of Proc. str.object_id is 70239372015840"
# => "end of Proc. str.object_id is 70239372015840"
的第一次Proc
被調用時,str
的Proc
內開始了引用原始對象,但隨後,該str *= 2
操作運行後,引用另一個對象。這是爲什麼?我預計原來的字符串會被修改,Proc
會繼續引用它。
'str * = 2'將一個新的字符串賦值給'str'(與'str = str * 2'相同),所以它得到一個新的對象id。 – lurker