Mark Mark - 1 year ago 69
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: &

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)

But is there a shorter/neater way?

Answer Source

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

letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']{|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::IGNORECASE)) # => ["Aaa", "BbB"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download