Counting subscribers with matching ZIP code, interests, and sex I am trying to cycle through a few of these blocks. They basically narrow down a number of people that fulfill a bunch of attributes.

I apologize if this seems really messy, but my database is really taking a toll processing this, and I know there's a better way. I'm just lost on strategy right now.

def count_of_distribution    
  #beginning with an array..
  array_of_users = []

  # any matching zip codes? ..
  # zip_codes
  @zip_codes = self.distributions.map(&amp;:zip_code).compact
  unless @zip_codes.nil? || @zip_codes.empty? 
    @matched_zips = CardSignup.all.map(&amp;:zip_code) &amp; @zip_codes
    @matched_zips.each do |mz| 
      CardSignup.find(:all, :conditions =&gt; ["zip_code = ?", mz]).each do |cs|
        array_of_users &lt;&lt; cs.id
      end
    end
  end

  # any matching interests?..
  # interest
  @topics = self.distributions.map(&amp;:me_topic).compact
  unless  @topics.nil? || @topics.empty?
    @matched_topics = MeTopic.all.map(&amp;:name) &amp; @topics
    @matched_topics.each do |mt|
      MeTopic.find(:all, :conditions =&gt; ["name = ?", mt]).each do |mt2|
        mt2.users.each do |u|
          array_of_users &lt;&lt; u.card_signup.id if u.card_signup
        end
      end
    end
  end

  # any matching sexes?..
  # sex
  @sexes = self.distributions.map(&amp;:sex).compact
  unless @sexes.nil? || @sexes.empty?
    @matched_sexes = CardSignup.all.map(&amp;:sex) &amp; @sexes
    @matched_sexes.each do |ms|
      CardSignup.find(:all, :conditions =&gt; ["sex = ?", ms]).each do |cs|
        array_of_users &lt;&lt; cs.id
      end
    end
  end

  total_number = array_of_users.compact.uniq

  return total_number
end
The first thing I notice is that you're calling map.{}.compact when you probably could be calling select{}, that is, you want to select from self.distribution. So that would replace 6 method calls with 3.

If you use select, it always returns an array and never a nil, so instead of unless X.nil or X.empty, you could use if X.any?, which would replace 6 method calls with three.

If you aren't using @matched_zips outside of this context, it makes no sense to assign a variable here. Instead of assigning, you could just use (CardSignup.all.map(&amp;:zip_code) &amp; @zip_codes).each do, which would spare you three variable assignments.