gpt4 book ai didi

ruby - ruby 中字符串替换方法的用途是什么?

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

我阅读了 ruby 中的 string 方法。我知道 replace 会将 string 替换为传递给它的 argument。但是我们也可以用一个简短而甜美的 = oparator 来做同样的事情。使用 replace 方法有什么意义?它只是一个 personnel choice 还是不同于 = operator?

    > a = "hell­o world­"
=> "hello world"
> a = "123"­
=> "123"
> a.replace(­"345")
=> "345"

最佳答案

使用 =

str = "cat in the hat"
str.object_id
#=> 70331872197480

def a(str)
str = "hat on the cat"
puts "in method str=#{str}, str.object_id=#{str.object_id}"
end

a(str)
in method str=hat on the cat, str.object_id=70331873031040

str
#=> "cat in the hat"
str.object_id
#=> 70331872197480

方法外的str和方法内的str的值是不同的对象。

使用 String#replace

str = "cat in the hat"
str.object_id
#=> 70331872931060

def b(str)
str.replace("hat on the cat")
puts "in method str=#{str}, str.object_id=#{str.object_id}"
end

b(str)
in method str=hat on the cat, str.object_id=70331872931060

str
#=> "hat on the cat"
str.object_id
#=> 70331872931060

方法外的str和方法内的str的值是同一个对象。

关于ruby - ruby 中字符串替换方法的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793869/

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