Mark Mark - 5 months ago 9
Ruby Question

Intersection of 2 array of strings with different upper and lower case

I want to get the intersection of 2 arrays of strings. The first array has different upper and lower case. The resulting array I want should respect the first arrays casing, but the comparison between the 2 should ignore the upper/lower case. E.g.

letters = ['Aaa', 'BbB', 'CCC']

permitted = ['aaa', 'bbb']


The result should be:

['Aaa', 'BbB']


Im doing:

letters.map(&:downcase) & permitted.map(&:downcase)


But this returns
['aaa', 'bbb']


What's a neat way of doing this? The longer way of doing it is:

letters.each { |letter|
if permitted.include?(letter.downcase)
accepted.push(letter)
end
}


But is there a shorter/neater way?

Answer

There's a method for comparing string in a case-insensitive manner, String#casecmp:

letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']

letters.select{|l| permitted.detect{|p| p.casecmp(l) == 0 } } # => ["Aaa", "BbB"]

You can also use regular expressions. :)

letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']

letters.grep(Regexp.new(permitted.join('|'), Regexp::IGNORECASE)) # => ["Aaa", "BbB"]