我試圖找到一種有效的方法來做到這一點。如果條目字串具有 Ph.D/Medical Doctor(這意味著“Dr.”的前綴)并且條目中包含名稱“Alex”,則回傳 True 的函式。
我嘗試了以下有效的代碼,但我認為應該有更有效的方法。我會很感激任何想法。
str1 = "Dr. Moses Alex"
str2 = "Dr. Ben Mora"
def match st
if st.include?('Dr.') and st.include?('Alex')
return true
else
return false
end
end
匹配(str1)#真
匹配(str2)#假
uj5u.com熱心網友回復:
我會使用String#match 嗎?用一個簡單的正則運算式:
r = /\ADr\.. \bAlex\b/
"Dr. J. Alex Knowitall".match?(r) #=> true
"He's Dr. J. Alex Knowitall".match?(r) #=> false
"Dr. J. Alexander Knowitall".match?(r) #=> false
我們可以以自由間距模式撰寫正則運算式以使其自檔案化:
r =
/
\A # match beginning of string
Dr\. # match literal "Dr."
. # match one or more characters, as many as
# possible, other than line terminators
\b # match a word boundary
Alex # match literal "Alex"
\b # match a word boundary
/x # assert free-spacing regex definition mode
對于任何解決方案,如果允許,一些字串可能會導致問題,例如,“Bubba Knowitall 博士和 Alex 是兄弟”。
uj5u.com熱心網友回復:
您的代碼可以簡化為:
def match(string)
string.start_with?('Dr.') && string.include?('Alex')
end
這是有效的,因為 Ruby 中的方法總是隱式回傳最后一條陳述句回傳的值。因此不需要顯式回傳。
uj5u.com熱心網友回復:
代碼看起來不錯。我唯一的反饋是關于“包含?”的使用。前綴的函式。嘗試使用“start_with?” 函式,這樣即使“博士”在字串中,你也不會得到 True 。
def match st
if st.start_with?('Dr.') and st.include?('Alex')
return true
else
return false
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396593.html
