2016-08-05 106 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,很好的建議。我編輯過。 –

相關問題