Finding the difference between strings in Ruby

前端 未结 5 981
长发绾君心
长发绾君心 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

    I understood the question in two ways. In case you wanted to do a string difference (word by word) which covers this case:

    teamOne = "Billy, Frankie, Tom, Stevie, John"
    teamTwo = "Billy, Frankie, Stevie, Tom, Zach"
    
    s1 = teamOne.split(' ')
    s2 = teamTwo.split(' ')
    
    diff = []
    s1.zip(s2).each do |s1, s2|
      if s1 != s2
        diff << s1
      end
    end
    
    puts diff.join(' ')
    

    Result is:

    Tom, Stevie, John
    

    Accepted answer gives:

    #
    

提交回复
热议问题