示例:
array1 = ["budget2017.doc", "accounting2017.doc", "mydogisdumb.doc"]
array2 = ["budget.doc", "accounting.doc", "imstupid.doc"]
我想比较两个数组的相似性,并从array1
返回相关元素。
array1.select { |x| x.include?(array2) }
我需要将结果作为["budget2017.doc", "accounting2017.doc"]
但很明显上面的工作没有成功,因为"budget.doc"
与"budget2017.doc"
不匹配。如果我可以匹配每个元素的前几个字符并从array1
返回相关元素,我就可以完成我需要的工作。
答案 0 :(得分:1)
array1 = %w[budget2017.doc accounting2017.doc mydogisdumb.doc]
array2 = %w[budget.doc accounting.doc imstupid.doc]
array1.select do |elem|
array2.any? do |ee|
s, e = ee.split('.')
elem.start_with?(s) && elem.end_with?(e)
end
end
#⇒ ["budget2017.doc", "accounting2017.doc"]
或者,效率更高:
selectors = array2.map { |e| e.split('.') }
array1.select do |elem|
selectors.any? do |(s, e)|
elem.start_with?(s) && elem.end_with?(e)
end
end
#⇒ ["budget2017.doc", "accounting2017.doc"]
答案 1 :(得分:0)
根据评论,查找array1
的所有元素,它们与array2
中的元素具有相同的前7个字符:
array1.select do |element|
array2.any? { |match_candidate| match_candidate.start_with? element[0...7] }
end
答案 2 :(得分:0)
arr1 = ["budget2017.doc", "acc2017.doc", "acc.doc", "budget2016.doc", "foo.doc"]
arr2 = ["budget.doc", "acc.doc", "foo.docx,", "goo.doc"]
a2 = arr2.map { |s| s.split('.') }
#=> [["budget", "doc"], ["acc", "doc"], ["foo", "docx,"], ["goo", "doc"]]
arr1.select { |s1| a2.any? { |pfx, sfx| s1 =~ /\A#{pfx}.*\.#{sfx}\z/ } }
#=> ["budget2017.doc", "acc2017.doc", "acc.doc", "budget2016.doc"]