數組我有遍歷紅寶石
array = ["this","is","a","sentence"]
我想打印一個字符串,如果在array
言我正在尋找一個詞相匹配的陣列。
例子:
array = ["this","is","a","sentence"]
array.each { |s|
if
s == "sentence"
puts "you typed the word sentence."
elsif
s == "paragraph"
puts "You typed the word paragraph."
else
puts "You typed neither the words sentence or paragraph."
end
此方法將打印:
"You typed neither the words sentence or paragraph."
"You typed neither the words sentence or paragraph."
"You typed neither the words sentence or paragraph."
"you typed the word sentence."
我希望它認識字"sentence"
和執行"you typed the word sentence."
。如果其中一個單詞不存在,它將執行else語句"you typed neither the words sentence or paragraph."
。
由於用戶匹配的單詞,該模式需要重複。自己的正則表達式是子字符串匹配,而不是單詞匹配。用'\ b'環繞模式使其成爲單詞匹配:'/ \ bfoo \ b'。由於搜索字符串不必拆分,基於正則表達式的搜索可能非常快。 –