2012-02-03 39 views
0

我有一個數組可以說如何確保某些元素不能進入陣列在Ruby中

array1 = ["abc", "a", "wxyz", "ab",......] 

如何確保既不如「一」(任何字符),「AB」(任2個字符),「abc」(任意3個字符),也不保存array1中的「that」,「this」,「what」等詞語以及任何犯規詞。

回答

3

這將刪除元素少於4個字符,也就是說這樣的,即,從array1什麼(如果我這樣做是正確):

array1.reject! do |el| 
    el.length < 4 || ['this', 'that', 'what'].include?(el) 
end 

這改變array1。如果使用reject(不含!),它將返回結果而不會更改array1

+0

感謝您的幫助!有效! – gkolan 2012-02-03 11:09:56

1

您可以打開並添加一個新的接口到Array類,該接口將禁止某些單詞。例如:

class Array 
    def add(ele) 
    unless rejects.include?(ele) 
     self.push ele 
    end 
    end 

    def rejects 
    ['this', 'that', 'what'] 
    end 
end 

arr = [] 

arr.add "one" 
puts arr 

arr.add "this" 
puts arr 

arr.add "aslam" 
puts arr 

輸出將是:

一個一個阿斯拉姆一個

,並注意單詞 「這個」 不添加。

+0

感謝您的回覆! – gkolan 2012-02-03 11:10:12

0

您可以創建一個停止列表。使用散列這將比數組更有效,因爲查找時間將與散列一致。對於數組,查找時間與數組中元素的數量成正比。如果你要檢查停用詞,我建議使用包含所有停用詞的散列。使用您的代碼,您可以執行以下操作:

badwords_a = ["abc", "a", "wxyz", "ab"] # Your array of bad words 
badwords_h = {}       # Initialize and empty hash 
badwords_a.each{|word| badwords_h[word] = nil} # Fill the hash 

goodwords = [] 

words_to_process = ["abc","a","Foo","Bar"] # a list of words you want to process 

words_to_process.each do |word| # Process new words 
if badwords_h.key?(word) 
else 
goodwords << word # Add the word if it did not match the bad list 
end 
end 

puts goodwords.join(", ") 
相關問題