加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 按引用/副本分配字符串?

发布时间:2020-12-17 04:34:57 所属栏目:百科 来源:网络整理
导读:谁能解释这种行为 情景1 str = "hello"str1 = strputs str #= helloputs str1 #= hellostr1 = "hi"puts str1 #= hiputs str #= hello 在这里,改变str1的值对str的值没有影响. 方案2 str = "hello"str1 = strstr1.gsub! "hello","whoa!"puts str1 #= whoaputs
谁能解释这种行为

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

`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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读