str = "Welcom to china" str1 = str puts str + " 1" puts str1 + " 1" def switch(str) str.replace("Happy to china") end switch(str.dup) puts str + " 2" puts str1 + " 2"
输出为
Welcom to china 1
Welcom to china 1
Welcom to china 2
Welcom to china 2
str = "Welcom to china" str1 = str puts str << " 1" puts str1 << " 1" def switch(str) str.replace("Happy to china") end switch(str.dup) puts str << " 2" puts str1 <<" 2"
输出为:
Welcom to china 1
Welcom to china 1 1
Welcom to china 1 1 2
Welcom to china 1 1 2 2
发现没有,二者是不一样的,str << 1,相当于执行了str.replace(str + "1"),修改了原始引用, 再打印出来,而str + "1"则不会修改原始引用值。