在Ruby中查找字符串之间的区别

时间:2009-01-08 21:53:40

标签: ruby string

我需要取两个字符串,比较它们,并打印它们之间的差异。

所以说我有:

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

$ teamOne.eql? teamTwo 
=> false

我想说“如果两个字符串不相等,请打印它们之间的不同之处。在这种情况下,我只是想打印”John。“

5 个答案:

答案 0 :(得分:16)

到目前为止,所有解决方案都忽略了第二个数组也可能包含第一个数组没有的元素的事实。 Chuck指出了一个修复方法(请参阅其他帖子的评论),但如果您使用套装,则会有更优雅的解决方案:

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"}>

如果需要,可以将此组转换回数组。

答案 1 :(得分:4)

如果您要比较的真实字符串与您提供的字符串类似,那么这应该有效:

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

答案 2 :(得分:4)

简单的解决方案:

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

当然这仅在您的字符串包含逗号分隔值时才有效,但这可以根据您的情况进行调整。

答案 3 :(得分:3)

您需要先排序,以确保不从较小的字符串中减去较大的字符串:

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)

答案 4 :(得分:0)

我从两个方面理解这个问题。如果您想进行涵盖这种情况的字符串差异(逐字):

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(' ')

结果是:

Tom, Stevie, John

接受的答案给出:

#<Set: {"Zach", "John"}>