2016-04-12 20 views
1

的字符串的示例文本的多個實例:我如何可以從Ruby的字符串中刪除文本時,有串

"6 red cables, 4 white cables, 9 blue cables" 

我想,這樣它讀取

刪除「電纜」
"6 red, 4 white, 9 blue" 

我看着slicesub方法,但它們只能去除「電纜」的第一個實例。有人能指引我朝着正確的方向嗎?

+0

考慮正則表達式? GSUB? – Radmation

+0

在您的字符串上調用gsub(「電纜」,「」)。或者更一般地說,可以像'def my_fun(s,x); s.gsub(x,'');結束' –

回答

7

您可以使用String#gsub

2.2.0 :003 > "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", "") 
=> "6 red, 4 white, 9 blue" 
-1

參考(VS GSUB比較分): http://www.dotnetperls.com/sub-ruby

回答

cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub("cables", '') 
Output "6 red , 4 white , 9 blue " 

說明:

value = "abc abc" 
# Gsub replaces all instances. 
value = value.gsub("abc", "---") 
puts value 

Output 

--- --- 

然後,您可以用同樣的方式擺脫逗號後的所有空格。

cleaner_value = cleaned_value.gsub(", ", ",") #replaces all instances 
output "6 red, 4 white, 9 blue" 

或者使用其他的解決方案,並做

cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", '') #notice the space before cables. May cause problems unless you know exactly the input 
+1

這將返回'「6紅色,4白色,9藍色」'。爲了去除這些空間,你需要將''電纜''改成''電纜'',但是你有@ Igor早期的解決方案。 –

+0

請不要折騰代碼。解釋它爲什麼有用以及它做了什麼。自己發佈代碼就好像把某人扔魚一樣。解釋就像教他們如何釣魚。後者更好,因爲他們會明白下一步該做什麼。 –

+0

@theTinMan我編輯了回覆。感謝您的建議,我喜歡這個比喻......似乎很熟悉:D – Radmation

相關問題