Looking for more to read? Check out the Archives!

Ruby Quick Tip: Compare and Combine Arrays

Given two Ruby arrays, how would you quickly compare or combine the elements?

In Ruby, this is really simple. Let’s say we have two arrays, representing members of a volleyball team and a softball team:

volleyball_team = ["Alex", "Karen", "Pete", "Alicia"]
softball_team = ["Karen", "Dante", "Pete"]

To see who is on both teams, we can use the ‘&’ operator and assign it to ‘both_teams’:

both_teams = volleyball_team & softball_team

This returns a new array that includes shared members of both teams, both_teams:

both_teams
=> ["Karen", "Pete"]

We can also use the - operator to find unique members…

Who plays softball, but not volleyball?

softball_team - volleyball_team
=> ["Dante"]

How about volleyball players absent from the softball team?

volleyball_team - softball_team
=> ["Alex", "Alicia"]

Or we can combine them with the + operator:

volleyball_team + softball_team
=> ["Alex", "Karen", "Pete", "Alicia", "Karen", "Dante", "Pete"]

Note that the combined list simply concatenates both arrays, so anyone on both team is listed twice. To fix that, we can call the uniq method. Let’s assign it to a variable (‘all_players’):

all_players = (volleyball_team + softball_team).uniq
=> ["Alex", "Karen", "Pete", "Alicia", "Dante"]

Simple features like this make Ruby a delightful programming language!


If you enjoyed this post, you might want to subscribe, so you don't miss the next one!