我想看看我是否可以检查2个具有相似值的数组,并返回2之间不同的项目。但是我有相似名称的项目,我希望也可以排除这些项目。 例如:
pantry = ["apples", "chedder cheese mild", "flour", "salt"]
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]
#=> desired return ["apples","bacon", "chocolate", "salt"]
我使用pantry - recipe #=> ["apples", "bacon", "chocolate", "salt", "cheddar cheese mild"]
答案 0 :(得分:2)
如果我们假设“相似”意味着多个单词串,除了最后一个单词之外的所有单词都是相同的......
pantry = ["apples", "chedder cheese mild", "flour", "salt"]
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]
result = (pantry + recipe).group_by{|x| x.slice(0,(x.index(/[\s][^\s]+\z/) || x.size))}
result = result.values.select{|x|x.size == 1}.flatten.sort
=> ["apples", "bacon", "chocolate", "salt"]