1

I have two arrays with different attributes for the objects contained in each.

participants

guests

The only field in common is provider_user_id

I want to do something like this

all_people = participants.map {|p| p.provider_user_id <> guests.provider_user_id }

This is probably not correct.

How can eliminate those participants who are also in the guests array?

2
  • Does all_people equate to guests who are not participants? Or are you wanting the combination of guests and participants but you want to avoid including the same person twice? Commented Sep 27, 2011 at 3:35
  • I want to avoid including the same person twice. Commented Sep 27, 2011 at 3:39

3 Answers 3

1

The following works, but I'd be interested if there's anything more concise.

guest_provider_ids = guest.map(&:provider_id)
non_guest_participants = participants.reject do |participant|
  guest_provider_ids.include?(participant.provider_user_id)
end
Sign up to request clarification or add additional context in comments.

Comments

1

Could work...

guests.each { |g| participants << g }
guests.uniq! { |g| g.provider_user_id }

This (should) combine the two arrays first, then removes any duplicates based on the key.

2 Comments

That said, I didn't test it out of pure tiredness. It's probably not a good time for me to being handing out advice on StackOverflow. ;)
Ah - it was added in 1.9.2. Warning: if you try using it on an older version, it'll just silently ignore the block.
1

Good answers but don't forget about |. For 1.9

p (guests | participants).uniq!{|g| g.provider_user_id}

For 1.8

p (guests | participants).reject{|p| guests.map{|g| g.provider_user_id}.include?(p.provider_user_id)}

1 Comment

Don't forget about the | character? I guess we'd better not forget the { and the } either, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.