红宝石中字符串替换方法的用途是什么?

时间:2016-08-05 16:26:12

标签: ruby string replace

我在string中阅读了ruby个方法。我了解replace会将string替换为传递给它的argument。但同样的事情我们可以做一个短而甜蜜的= oparator。使用replace方法有什么意义?它只是personnel choice或与=运算符不同?

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

3 个答案:

答案 0 :(得分:2)

这行代码将变量a更改为指向新字符串:

a = "new string"

这行代码实际上更改了a(可能还有其他变量)指向的字符串对象:

a.replace "new string"

答案 1 :(得分:2)

使用=

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的值是同一个对象。

答案 2 :(得分:1)

用例实际上只是为了实现与其他语言中的pass-by-reference类似的东西,其中变量的值可以直接更改。因此,您可以将String传递给方法,并且该方法可以将字符串完全更改为其他内容。

def bar(bazzer)
  bazzer.replace("reference")
end

bar(baz)

=> It's reference because local assignment is above the food chain , but it's clearly pass-by-reference

这是有道理的。