Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用'操作Ruby中的字符串+';和';插入';_Ruby_Variables - Fatal编程技术网

使用'操作Ruby中的字符串+';和';插入';

使用'操作Ruby中的字符串+';和';插入';,ruby,variables,Ruby,Variables,我有以下Ruby代码: a = "Python" b = a.+"xyz" c = b.insert(2, "oo") puts a puts b puts c 我期待着: Python Pythonxyz Pyoothonxyz 但我得到: Python Pyoothonxyz Pyoothonxyz 有人能帮我吗?我刚开始学习Ruby,这有点令人费解。谢谢你的帮助 a = 'Python' b = a + 'xyz' 作为,String#+返回一个新字符串,该字符串是接收器和参数的串

我有以下Ruby代码:

a = "Python"
b = a.+"xyz"
c = b.insert(2, "oo")
puts a
puts b
puts c
我期待着:

Python
Pythonxyz
Pyoothonxyz
但我得到:

Python
Pyoothonxyz
Pyoothonxyz
有人能帮我吗?我刚开始学习Ruby,这有点令人费解。谢谢你的帮助

a = 'Python'
b = a + 'xyz'
作为,
String#+
返回一个新字符串,该字符串是接收器和参数的串联(boldemphasis):

str+other\u str
→ <代码>新建\u str 连接-返回一个新字符串,其中包含连接到
str
other\u str

因此,
a
b
引用不同的字符串

由于,
String#insert
修改了字符串,因此字符串仍然是相同的,只是内容不同(粗体强调):

insert(索引、其他str)
→ <代码>str 在给定的
索引处的字符前插入
other_str
修改
str
。[……]

因此,
b
c
引用相同的字符串


换句话说,代码中总共有两个字符串。一个被
a
引用,另一个被
b
c
引用
insert
函数正在更改原始字符串。这就是它的工作方式,通常在Ruby中,如果您不想更改原始对象,则需要添加
添加到方法,但默认情况下,
insert
的作用与方法相同。复制
b
c=b.dup.insert(2,“oo”)
,请参见下面的@Jörg W Mittag答案。多亏了你们两位,这是非常有价值的见解
c = b.insert(2, 'oo')