2016-07-26 146 views

回答

1

您正在尋找sub!

str = "hi ram hi shyam hi jhon" 

str.sub!("hi ", "") 
#=> "ram hi shyam hi jhon" 

str.sub!("hi ", "") 
#=> "ram shyam hi jhon" 

str.sub!("hi ", "") 
#=> "ram shyam jhon" 

套內你做什麼修改原始的字符串,這不是這個例子的樣子,你可能想使用sub來代替,並且一個額外的變量

2
str = "hi ram hi shyam hi jhon" 

要刪除一個發生:

str.sub('hi', '').strip.squeeze 
#⇒ "ram hi shyam hi jhon" 

要刪除n個出現:

n.times { str.replace(str.sub('hi', '').strip.squeeze) } 
4

我假設你要刪除的所有單詞重複出現,而不是僅僅"hi"。這有兩種方法。

1使用String#reverseArray#reverseArray#uniq

str = "hi shyam ram hi   shyam hi jhon" 

str.split.reverse.uniq.reverse.join(' ') 
    #=> "ram shyam hi jhon" 

uniq狀態的文檔: 「self遍歷有序,並第一次出現,保持爲」

2使用正則表達式

r =/
    \b  # match a word break 
    (\w+) # match a word in capture group 1 
    \s  # match a trailing space 
    (?=  # begin a positive lookahead 
     .* # match any number of characters 
     \s # match a space 
     \1 # match the contents of capture group 1 
     \b # match a word break 
    )  # end the positive lookahead 
    /x  # free-spacing regex definition mode 

str.gsub(r, '') 
    #=> "ram   shyam hi jhon" 

要刪除多餘的空格的正則表達式定義的第三行改變\s\s+

+1

這傢伙在開玩笑說我脫掉了我的藥! Upvoted :) – mudasobwa