Check if two arrays have the same contents (in any order)

前端 未结 9 1706
我在风中等你
我在风中等你 2020-12-24 04:13

I\'m using Ruby 1.8.6 with Rails 1.2.3, and need to determine whether two arrays have the same elements, regardless of whether or not they\'re in the same order. One of the

9条回答
  •  一向
    一向 (楼主)
    2020-12-24 04:52

    One approach is to iterate over the array with no duplicates

    # assume array a has no duplicates and you want to compare to b
    !a.map { |n| b.include?(n) }.include?(false)
    

    This returns an array of trues. If any false appears, then the outer include? will return true. Thus you have to invert the whole thing to determine if it's a match.

提交回复
热议问题