Sean
Sean

Reputation: 1

Ruby - if element in array partly matches with element from another array

Example:

array1 = ["budget2017.doc", "accounting2017.doc", "mydogisdumb.doc"]
array2 = ["budget.doc", "accounting.doc", "imstupid.doc"] 

I would like to compare the two arrays for similarity and return the associated element from array1.

array1.select { |x| x.include?(array2) }

I need the result to be a new array with ["budget2017.doc", "accounting2017.doc"]

But obviously the above won't work because "budget.doc" is not a match with "budget2017.doc". I could accomplish what I need if I could just match the first few characters of each element and return the associated element from array1.

Upvotes: 0

Views: 625

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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"]

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

As per the comments, finds all elements of array1, which have the same first 7 characters as an element out of array2:

array1.select do |element|
  array2.any? { |match_candidate| match_candidate.start_with? element[0...7] }
end

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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"] 

Or, a bit more efficient:

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"] 

Upvotes: 1

Related Questions