在这个 Ruby 1.9.2 代码中:
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:0x007fc3c1a32050@(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
调用 to 时,str
在Proc
开始时引用原始对象,但随后在str *= 2
运行操作后引用另一个对象。这是为什么?我预计原始字符串会被修改,并且Proc
会继续引用它。