如何遍历字符串和字符串数组以查找匹配项?

问题描述

| 我试图遍历标题字符串与字符串数组,并查看该数组中的哪些匹配。 我的代码工作正常,但是我不确定这是否是最有效的方法。 重要的是,数组中的字符串不必与标题中的短语完全匹配。只要标题中每个单词,它们的顺序都可以。任何帮助都会很棒。
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\"]
    

解决方法

        您可以执行以下操作:
>> require \'set\'
=> true
>> title = \"Apple Iphone 4 Verizon\"
=> \"Apple Iphone 4 Verizon\"
>> all_pids = [\"iphone apple\",\"verizon iphone\",\"iphone 3g\",\"iphone 4\",\"cool iphone\"]
=> [\"iphone apple\",\"cool iphone\"]
>> title_set = Set.new(title.downcase.split)
=> #<Set: {\"apple\",\"iphone\",\"4\",\"verizon\"}>
>> all_pids.select { |pid| Set.new(pid.downcase.split).subset? title_set }
=> [\"iphone apple\",\"iphone 4\"]
您可以使用数组差异来做非常相似的事情,但是集合可能会更快地实现,因为它们是作为哈希实现的。     ,        在我看来,您想找到由与标题中的字符串严格相交的字符串组成的字符串。
Array#-
执行设定差运算。
[2] - [1,2,3] = []
[1,3] - [2] = [1,3]
title = \"Apple Iphone 4 White Verizon\"
all_pids = [\"iphone 3gs\",\"iphone white 4\",\"iphone verizon\",\"black iphone\",\"at&t      iphone\"]
set_of_strings_in_title = title.downcase.split
all_pids.find_all do |pid|
  set_of_strings_not_in_title = pid.downcase.split - set_of_strings_in_title 
  set_of_strings_not_in_title.empty?
end
编辑:将#find更改为#find_all以返回所有匹配项,而不仅仅是第一个。