Finding the difference between strings in Ruby

前端 未结 5 980
长发绾君心
长发绾君心 2021-02-07 19:00

I need to take two strings, compare them, and print the difference between them.

So say I have:

teamOne = \"Billy, Frankie, Stevie, John\"
teamTwo = \"Bi         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 19:44

    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 # => #
    

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

提交回复
热议问题