2015-08-22 87 views
0

正如這個標題所暗示的那樣,我希望得到一些字符,並檢查它們是否屬於任何字符串。如果我想,例如,「!」被禁止,然後string.replace("",word_with_!)。如果forbidden_​​chars是一個數組,我該如何檢查禁止的字符?從包含某個字符的紅寶石中清除單詞

forbidden_chars = ["!",",",...] 

check ARRAY (it is the string split into an array) for forbidden chars 
erase all words with forbidden chars 

任何人都可以幫助我嗎?我只是考慮在卡片上搜索單詞並在檢索答案中強制性地檢索索引。非常感謝你:)

+0

看'gsub'方法 - http://ruby-doc.org/core-2.2.3/String.html#method-i-gsub –

回答

3
string = 'I like my coffee hot, with no sugar!' 

forbidden_chars = ['!', ','] 
forbidden_chars_pattern = forbidden_chars.map(&Regexp.method(:escape)).join('|') 

string.gsub /\S*(#{forbidden_chars_pattern})\S*/, '' 
    # => "I like my coffee with no " 

的想法是儘可能多的非空格字符匹配儘可能\S*,其次是任何被禁止的字符(!|,),隨後又爲許多非空白字符儘可能。

我們需要Regexp.escape的原因是當禁止的字符具有特殊的正則表達式含義時(如.)。

+0

假設'string ='我的寵物斑馬被命名爲「Hank」' '和 forbidden_​​chars = ['z'] –

+0

@CarySwoveland,偉大的一點!修正了,謝謝。 – ndn

0
​​

注意這不保留間距"I""like"之間,但如果在string有沒有多餘的空格返回有沒有多餘的空格的字符串。