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

后端 未结 1 1481
名媛妹妹
名媛妹妹 2021-02-04 02:01

Demo (I expect result [3]):

[1,2] - [1,2,3] => []    # Hmm
[1,2,3] - [1,2] => [3]   # I see

a = [1,2].to_set   => #
b =         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 02:13

    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                  # => #
    

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

    ( a | b ) - ( a & b )  # => #
    

    0 讨论(0)
提交回复
热议问题