Compare lists/arrays in Ruby

Ever stumbled over the problem, that you have two lists (for clarities sake, list A and B) and want to know what elements are missing from list B that are in list A?

With Ruby this problem can solved in a rather elegant way, by using set algebra. Let me show you how with a few examples. For the remainder of this blogpost I will assume the following values for our two lists:

list_a = [ :a, :b, :c ]

list_b = [ :b, :c, :d ]

Now lets assume you only want to have the items that are missing in list A. You can get the elements like this:

list_a - ( list_a & list_b ) # => :d:a

The analog is true for B. And if you want to find the elements that are either only in A or B you can do just as easily:

( list_a | list_b ) - ( list_a & list_b ) # => :a, :d


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: