Ruby: Check if two arrays have any elements in common
Say you have two teams and you want to see if they have any players in common.
How do you do this in Ruby?
You might try something like this:
1 2 3 |
(team_one.players - team_two.players).size < team_one.players.size |
Or something even more complex like this:
1 2 3 4 5 |
team_one.player_ids.any? { |pid| team_two.player_ids.include?(pid) }
|
However, you would be creating useless complexity. Instead you can just do this:
1 2 3 4 5 |
(team_one.player_ids & team_two.player_ids).any? |
This uses the intersection operator. Which returns the elements in common between two arrays, removing the duplicates. This is useful.
Also be aware of array_one | array_two, which combines the arrays, removing duplicates.
October 14, 2009
