{"id":2925,"date":"2012-03-23T09:18:01","date_gmt":"2012-03-23T13:18:01","guid":{"rendered":"http:\/\/teamtutorials.com\/?p=2925"},"modified":"2012-04-04T13:36:56","modified_gmt":"2012-04-04T17:36:56","slug":"simple-array-comparison-with-ruby","status":"publish","type":"post","link":"https:\/\/teamtutorials.com\/web-development-tutorials\/simple-array-comparison-with-ruby","title":{"rendered":"Simple Array Comparison with Ruby"},"content":{"rendered":"
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.<\/p>\n
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.<\/p>\n
\r\nrequire 'set'\r\n\r\n#create array\r\na = [1,2,3,4]\r\nb = [2,3,5,6]\r\n\r\n#convert to set\r\na.to_set\r\nb.to_set\r\n\r\n#remove items in b from a\r\ndiff = (a - b)\r\n\r\n#output what ever is left\r\nputs diff\r\n<\/pre>\nSince 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:<\/p>\n
\r\na = Set.new[1,2,3]\r\n#or\r\na = [1,2,3].to_set\r\n<\/pre>\nMainly 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<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"
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 … Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2929,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[156,17],"tags":[153,155,152,154],"yoast_head":"\n
Simple Array Comparison with Ruby<\/title>\n\n\n\n\n\t\n\t\n\t\n