开发者

how to create an array that excludes items from another array in Ruby

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 开发者_如何学C<> guests.provider_user_id }

This is probably not correct.

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


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


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.


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)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜