How to 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 where I find everything that matches, but it also shows me duplicates.

Any ideas?

I am trying to find the number of people who have subscribed to a card with the corresponding zip code, to my preferred zip code.

+4
source share
1 answer

Array#reject again to the rescue! 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 operators like you. & will return a new array with objects in both, | will connect 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 applies to the Rails model, you might want to do this as a choice. 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 beautiful 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 ..)

+7
source

Source: https://habr.com/ru/post/1344300/


All Articles