【发布时间】:2011-05-28 03:30:35
【问题描述】:
我正在尝试用一个字符串数组遍历一个标题字符串,并查看数组中的哪些匹配。
我的代码运行良好,但我不确定这是否是最有效的方法。
重要的是数组中的字符串不必与标题中的短语完全匹配。只要每个单词都在标题中,它们就可以按任何顺序排列。任何帮助都会很棒。
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 apple”中的单词在标题中,顺序无所谓
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"]
【问题讨论】: