Pages Navigation Menu

Simple Array Comparison with Ruby

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.

  • http://twitter.com/spyderman4g63 John Ward

    ruby is cool

  • http://www.graphicdesignblog.org/web-design/ Web Design

    Good sort of techniques and thanks for bringing this stuff here.

  • http://www.graniteint.com/ Graniteint

    This article serves as a good basis to gain knowledge.

  • http://worldmusicdays2014.info/ Worldmusicdays

    Thank for sharing your very valuable input

  • http://www.acowellsite.info/ Acowellsite

    I find it very interesting.

  • flalaw jobfind

    This is one of the awesome material