你可以猴子補丁String
做這樣的事情
class String
def include_all?(*args)
args.map{|arg| self.include?(arg)}.reduce(:&)
end
end
然後調用像
action = "look a dog bed for sale"
action.include_all?("look","bed")
#=> true
action.include_all?("look","bed","fish")
#=> false
這樣做是爲你提供它需要儘可能多的參數,並使用它們放入一個Array
splat *
然後檢查以確定每個包含在String
中。然後,它降低了他們使用&
運營商的單一值,使之轉化爲
action = "look a dog bed for sale"
action.include_all?("look","bed")
#args = ["look","bed"]
#args.map{|arg| action.include?(arg)}
#=> [true,true]
#true & true
#=> true
action.include_all?("look","bed", "fish")
#args = ["look","bed","fish"]
#args.map{|arg| action.include?(arg)}
#=> [true,true,false]
#true & true & false
#=> false
其他建議是更加標準程序。我只想指出新的紅寶石主義者,改變一個階級是一個相當簡單的過程。使用你自己的風險
你能詳細說明什麼是/不工作?添加輸入,預期行爲和實際行爲將會很有幫助。 – Max 2014-10-10 14:44:19
如果您需要檢查數組中多個值的成員關係,則需要像'action.include?('look')&& action.include?('bed')'或者'smarter'['look' 「牀」。所有? {| O | action.include? o}'或者更邪惡的'''''看','牀']。 &action.method(:include?)' – 2014-10-10 14:53:47