在 Ruby 中查找字符串之间的差异 [英] Finding the difference between strings in Ruby

查看:39
本文介绍了在 Ruby 中查找字符串之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

所以说我有:

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

$ teamOne.eql? teamTwo 
=> false

我想说如果两个字符串不相等,则打印它们之间不同的任何内容.在这种情况下,我只是想打印John".

I want to say "If the two strings are not equal, print whatever it is that is different between them. In this case, I'm just looking to print "John."

推荐答案

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

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.

这篇关于在 Ruby 中查找字符串之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆