hello puts str1 #=> hello str1 = "hi" puts s-6ren">
gpt4 book ai didi

ruby - 通过引用/复制进行字符串赋值?

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:23 26 4
gpt4 key购买 nike

任何人都可以解释这种行为

场景 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

在上述情况下,strstr1 持有对同一对象的引用,由 object_id 证明。现在你在下面的例子中使用局部变量 str1 来保存一个新对象 "hi",这也由两个不同的 object_id 证明

str1 = "hi"
puts str1 #=> hi
puts str #=> hello
p str.object_id #=> 15852348
p str1.object_id #=> 15852300

场景 2

`String#gsub!说:

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

关于ruby - 通过引用/复制进行字符串赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16230255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com