Finding the difference between strings in Ruby

If the real string you are comparing are similar to the strings you provided, then this should work:

teamOneArr = teamOne.split(", ")
=> ["Billy", "Frankie", Stevie", "John"]
teamTwoArr = teamTwo.split(", ")
=> ["Billy", "Frankie", Stevie"]
teamOneArr - teamTwoArr
=> ["John"]

All of the solutions so far ignore the fact that the second array can also have elements that the first array doesn't have. Chuck has pointed out a fix (see comments on other posts), but there is a more elegant solution if you work with sets:

require 'set'

teamOne = "Billy, Frankie, Stevie, John"
teamTwo = "Billy, Frankie, Stevie, Zach"

teamOneSet = teamOne.split(', ').to_set
teamTwoSet = teamTwo.split(', ').to_set

teamOneSet ^ teamTwoSet # => #<Set: {"John", "Zach"}>

This set can then be converted back to an array if need be.

Tags:

String

Ruby