我想通過一個字符串數組來循環標題字符串,並查看數組中的哪一個匹配。如何通過字符串數組來查找匹配字符串?
我的代碼工作正常,但我不知道它是否是最有效的方式來做到這一點。
重要的是數組中的字符串不必完全匹配標題中的短語。只要標題中包含每個詞,它們可以以任意順序排列。任何幫助都會很棒。
EX.title = "Apple Iphone 4 Verizon"
array = ["iphone apple, verizon iphone", "iphone 3g", "iphone 4", "cool iphone"]
我需要它返回["iphone apple", "verizon iphone", "iphone 4"]
。在字符串「Verizon的iPhone」和「iphone蘋果」的話是在標題中,順序並不重要
results = []
#Loop through all the pids to see if they are found in the title
all_pids = ["iphone 3gs", "iphone white 4", "iphone verizon", "black iphone", "at&t iphone"]
title = "Apple Iphone 4 White Verizon"
all_pids.each do |pid|
match = []
split_id = pid.downcase.split(' ')
split_id.each do |name|
in_title = title.downcase.include?(name)
if in_title == true
match << name
end
end
final = match.join(" ")
if final.strip == pid.strip
results << pid
end
end
print results
當我運行這一點,打印什麼,我需要["iphone white 4", "iphone verizon"]
我認爲,使用Set的這種替代方法更好,更清潔,沒有使用不必要的輔助變量。 – asaaki 2011-05-31 23:56:38
謝謝..這工作完美。 – blakecash 2011-06-03 05:59:26
很高興聽到! :-)如果這是你正在尋找的答案,你應該接受它(選票旁邊的勾號),以便其他人知道這個問題已經得到了答覆。 – 2011-06-03 08:01:03