我有這行代碼:紅寶石超過2替代在或運營商
if self.include?("van " || "de " || "von ")
當或運營商的第三替代爲真爲什麼不包括該行之後的塊執行?
當我的字符串是"von wartburg"
塊不會執行,但是當我的字符串包含"van"
或"de"
然後它。
我有這行代碼:紅寶石超過2替代在或運營商
if self.include?("van " || "de " || "von ")
當或運營商的第三替代爲真爲什麼不包括該行之後的塊執行?
當我的字符串是"von wartburg"
塊不會執行,但是當我的字符串包含"van"
或"de"
然後它。
self.include?("van " || "de " || "von ")
將ALWAYS評估爲
self.include?("van ")
爲什麼?由於||
的工作原理。
"van " || "de " || "von "
# ↑↑↑↑↑↑ evaluates to "van " and does not give a slightest shoe about the rest
請參閱String#include
- 它接受一個子字符串和偏移量作爲參數。
你需要的是以下幾點:
["van ", "de ", "von "].any? { |substring| self.include?(substring) }
我想你想要的是
if self.include?("van ") || self.include?("de ") || self.include?("von ")
具有調用內部的||
到include?
使得它僅分析第一個字符串。您想針對每種情況測試include?
。
爲什麼downvotes? –
那麼它不爲「德」工作,要麼
2.3.0 :004 > "van test".include?("van " || "de " || "von ")
=> true
2.3.0 :005 > "de test".include?("van " || "de " || "von ")
=> false
2.3.0 :006 > "von test".include?("van " || "de " || "von ")
=> false
當您運行String#include?("van " || "de " || "von ")
你只傳遞一個參數傳遞給函數: "van " || "de " || "von "
。
Boolean OR(||
)將返回列表中第一個計算結果爲true的元素。所以這與String#include?("van ")
嚴格相同。
我知道只有兩種方式可以做你試圖在短短的一行做:
你可以讓子的一個表來測試和使用any?
在它
["van ", "de ", "von "].any? { |s| string.include?(s) }
或者你也可以使用正則表達式(其中或者操作符(|
)完全按照你想要的)
/van |de |von/=~ string
「or'de'then it does」 - nope。它只適用於「麪包車」 –
感謝英語更正;) – thiebo