2016-08-05 53 views
2

我在ruby中读取string方法。我明白replace将取代string与传递给它的argument。但同样的事情,我们可以做一个简短而甜美的= oparator也。使用replace方法有什么意义?它只是一个personnelchoice或它不同于=运营商?ruby​​中字符串替换方法的用法是什么?

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

回答

1

使用情况真的只是,实现的东西很像传递通过参考其他语言,其中一个变量的值,可以直接更改。所以你可以传递一个字符串到一个方法,该方法可能会完全改变字符串到别的东西。

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 

这是有道理的。

2

这行代码改变可变a指向一个新的字符串:

a = "new string" 

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

a.replace "new string" 
+0

我同意@David @John如果你看看C源代码(http://ruby-doc.org/core-1.9.3/String.html#method-i-replace),你会看到你的情况下的'a'不是重新初始化,把'replace'想象成改变这个变量。 –

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方法内是相同的对象。

+0

或许值得一提的是'object_id'是一个很好的方法来发现一个对象是否已经改变。 – tadman

+0

@tadman,很好的建议。我编辑过。 –

相关问题