谁能解释这种行为
情景1
str = "hello" str1 = str puts str #=> hello puts str1 #=> hello str1 = "hi" puts str1 #=> hi puts str #=> hello
在这里,改变str1的值对str的值没有影响.
方案2
str = "hello" str1 = str str1.gsub! "hello","whoa!" puts str1 #=> whoa puts str #=> whoa
不是gsub!只影响str1?为什么要改变str?如果str1只保存对str的引用,那么为什么在Scenario-1中值不会改变?
解决方法
仔细看下面:
情景1
str = "hello" str1 = str puts str #=> hello puts str1 #=> hello p str.object_id #=>15852348 p str1.object_id #=> 15852348
在上面的情况下,str和str1保持对object_id证明的相同对象的引用.现在,在下面的情况下使用局部变量str1来保存一个新对象“hi”,这也是由两个不同的object_ids证明的.
str1 = "hi" puts str1 #=> hi puts str #=> hello p str.object_id #=> 15852348 p str1.object_id #=> 15852300
方案2
Performs the substitutions of String#gsub in place,returning str,or nil if no substitutions were performed. If no block and no replacement is given,an enumerator is returned instead.
str = "hello" str1 = str str1.gsub! "hello","whoa!" puts str1 #=> whoa puts str #=> whoa p str.object_id #=>16245792 p str1.object_id #=>16245792