Trip
Trip

Reputation: 27114

How do I match two arrays with duplicates in Ruby?

I know this removes duplicates :

@email.distributions.map(&:zip_code) & CardSignup.all.map(&:zip_code)

But I want to do the same thing, where I find anything that matches, but it also shows me duplicates.

Any ideas?

I am trying to find the amount of people who signed up for a card that have a matching zip code to a zip code preference I placed.

Upvotes: 4

Views: 4123

Answers (1)

fx_
fx_

Reputation: 1932

Array#reject to the rescue, again! Like Array#map, it accepts blocks, allowing you to do something like this:

zip_codes = CardSignup.all.map(&:zip_code)
@email.distributions.reject{|o| !zip_codes.include?(o.zip_code)}

Oh, but of course, if you like finding more elegant ways, always consider the operators like you already did. & will return a new array with objects that are in both, | will join and remove duplicates.

ruby-1.9.2-p0 > [1,2] | [2,3]
 => [1, 2, 3] 
ruby-1.9.2-p0 > [1,2] & [2,3]
 => [2] 

Edit: as Tokland said in the comments, since this is applied on a Rails Model, you may want to consider doing it as a select. Like this -

zip_codes = CardSignup.all.map(&:zip_code)
@email.distributions.where('zip_code IN (?)', zip_codes)

Or, do it with an INNER JOIN. Doesn't look as pretty though.

@email.distributions.joins('INNER JOIN card_signups ON card_signups.zip_code = email_distributions.zip_code').all

(If the table for @email.distributions is email_distributions..)

Upvotes: 7

Related Questions