Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created June 7, 2012 10:33
Show Gist options
  • Save mahemoff/2888098 to your computer and use it in GitHub Desktop.
Save mahemoff/2888098 to your computer and use it in GitHub Desktop.
subtract.rb

This is like a-b, where a and b are sets, but it effectively uses a case-insensitive comparison function.

The reason for this is that Rails/MySQL find_by is case-insensitive. So if you have a data feed where someone's changed only the case, but don't want that to actually affect anything, you can use this function to see if there's a real difference (beyond just flipping the case).

def case_insensitive_subtract(a,b)
a_items_by_lowercase = {}
a.each { |item| a_items_by_lowercase[item.downcase] = item }
b_items_by_lowercase = {}
b.each { |item| b_items_by_lowercase[item.downcase] = item }
lowercase_diff = a_items_by_lowercase.keys - b_items_by_lowercase.keys
result = Set.new
lowercase_diff.each { |lowercase| result.add a_items_by_lowercase[lowercase] }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment