How to do sane “set-difference” in Ruby?

你离开我真会死。 提交于 2019-12-02 22:35:42

The - operator applied to two arrays a and b gives the relative complement of b in a (items that are in a but not in b).

What you are looking for is the symmetric difference of two sets (the union of both relative complements between the two). This will do the trick:

a = [1, 2, 9]
b = [1, 2, 3]
a - b | b - a          # => [3, 9]

If you are operating on Set objects, you may use the overloaded ^ operator:

c = Set[1, 2, 9]
d = Set[1, 2, 3]
c ^ d                  # => #<Set: {3, 9}>

For extra fun, you could also find the relative complement of the intersection in the union of the two sets:

( a | b ) - ( a & b )  # => #<Set: {3, 9}>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!