Pages Navigation Menu
 

Simple Array Comparison with Ruby

Beautiful WordPress Themes

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.

6 Comments

  1. ruby is cool

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

  3. This article serves as a good basis to gain knowledge.

  4. Thank for sharing your very valuable input

  5. I find it very interesting.

  6. This is one of the awesome material

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>