0

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

4

1 回答 1

2

When you assign:

str = "abc"

str gets an object id. If you did this:

str[1] = 'd'

Then the object id of str wouldn't change because you are modifying the existing string.

However, if you do any of these:

str = "123"
str = str * 2
str *= 2

You are creating/assigning a new string to str, so it's object id changes.

于 2013-08-31T16:28:56.177 回答