Finding the difference between strings in Ruby

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

    easy solution:

     def compare(a, b)
       diff = a.split(', ') - b.split(', ')
       if diff === [] // a and b are the same
         true
       else
         diff
       end
     end
    

    of course this only works if your strings contain comma-separated values, but this can be adjusted to your situation.

    0 讨论(0)
  • 2021-02-07 19:25

    You need to sort first to ensure you are not subtracting a bigger string from a smaller one:

    def compare(*params)
       params.sort! {|x,y| y <=> x}
       diff = params[0].split(', ') - params[1].split(', ')
       if diff === []
          true
       else
          diff
       end 
    end
    
    puts compare(a, b)
    
    0 讨论(0)
  • 2021-02-07 19:41

    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"]
    
    0 讨论(0)
  • 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 # => #<Set: {"John", "Zach"}>
    

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

    0 讨论(0)
  • 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:

    #<Set: {"Zach", "John"}>
    
    0 讨论(0)
提交回复
热议问题