Comparing array of strings with Ruby
27. April, 2011 Leave a comment
A while ago I made a blogpost on how to compare two arrays with each other. Unfortunately it doesn’t support the comparison of strings in an array. At least until recently I thought that would be the case.
So how is it done? Well lets say you want to start a flamewar between your favorite editor and the you-know-which-one. So you make two lists of either sides:
vim_users = [ "Ann", "Berta", "Charles" ]
emacs_users = [ "Charles", "Donald", "Elane" ]
Now you do know that some like to use both but they will only hinder a good argumentation i.e. flamewar, so how do we get the hardcore users of each group?
If we could use some good old logic it would result in a simple XOR i.e. in Ruby the ‘^’ symbol. This is provided by the set library. So lets get some code to explain this a bit more:
use 'set' #reference the libraries
vim_users = [ "Ann", "Berta", "Charles" ]
emacs_users = [ "Charles", "Donald", "Elane" ]
result_set = vim_users.to_set ^ emacs_users.to_set # Convert and XOR the two arrays
You can even convert the set back to a normal array:
result = result_set.to_a
Now you have your list of people that you can invite to your flamewar. Want to know who will be on which side? Well here is the base logic to get it achieved:
A - A & B # => elements present in A but not in B
In my little example this would look like this:
vim_only_rooters = vim_users.to_set - (vim_users.to_set & emacs_users.to_set)
emacs_only_rooters = emacs_users.to_set - (emacs_users.to_set & vim_users.to_set)
I hope this will help other people than me on how to solve this problem in a *my opinion* nice way.