Navigation
« Operating System Deficit Disorder | Main | Ubuntu RVM Rails pre install »
Monday
Nov212011

Intersection of collection of arrays

Ok, so tonight I was working on the Tags portion of this (my old site) site. I wanted to include a list of tags on the right side of the page. This is pretty typical of blogging engines. That part was easy for the most part. I then wanted to filter the posts on the main page based on the tag clicked. This too was pretty easy by just passing back the name of the tag and filtering.

Here is where the problems began. I thought to myself "Wouldn't it be cool if they were filters?". Think about it. If a user clicks on ruby, then I only show ruby posts. But what if a user only wants to see ruby and rails posts? Shouldn't be too difficult, right? Well, I was wrong. It took me quite some time to get the logic down on how I wanted the query to look. I wrestled with the Rails Query Engine for a while. I kind of expected more magic from it to be honest. I couldn't figure out how to have multiple 'tag.name = ?', tagname1 filters. I ended up opting to query for the associated post ids from a Tag.where(...) query and then finding the intersection of those post_ids.

Ok, now to the REAL PROBLEM. I had an array of arrays that I needed to find the intersection of. I assumed there would be a method available already to do this and as far as I know, there is, but I couldn't find one so here is what I came up with.

def intersect_arrays(arrays)
  result = []
  arrays.compact.each do |a|
    if result.empty?
      result = a
    else
      result = result & a
    end
  end
  result
end

I wouldn't consider myself a seasoned Rubyist at this point so I wouldn't be surprised if there was either a method already available to do this or a better approach to doing this; but, it gets the job done for now. I did get the idea for handling this problem from the PullMonkey.com post. I didn't like the idea of using an inline eval method call so I created this method to get around it.

Another day, another problem, another hack.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Textile formatting is allowed.