I ran into a task where I needed to find the differences with some data. Since I’ve not spent much time with ruby I decided to give it a shot. It was surprisingly simple to do what I needed to do in ruby. I’m not going to post the entire details right now, but wanted to leave a quick note here on comparing arrays.
I stored the data I needed to evaluate into an array. I wanted to find the items that appeared in array A but not in array B. Basically all we need to do is included the ruby set library and then it is very very simple to do this.
require 'set' #create array a = [1,2,3,4] b = [2,3,5,6] #convert to set a.to_set b.to_set #remove items in b from a diff = (a - b) #output what ever is left puts diff
Since I already had my data in an array, I just converted it to a set object. Technically if you are creating a set you could use either of these methods:
a = Set.new[1,2,3] #or a = [1,2,3].to_set
Mainly I wanted to add this little snippet so I can refer back to this at some point, but I figured it may help someone else who is new to ruby. For more information on set check out the set documentation.
Johnathan Ward is an experienced developer and consultant that writes tutorials to help other developers. In his day job, he is an IBM Watson Consultant with several years of experience deploying and customizing Watson Explorer solutions.