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

前端 未结 9 1689
我在风中等你
我在风中等你 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:59

    If you expect [:a, :b] != [:a, :a, :b] to_set doesn't work. You can use frequency instead:

    class Array
      def frequency
        p = Hash.new(0)
        each{ |v| p[v] += 1 }
        p
      end
    end
    
    [:a, :b].frequency == [:a, :a, :b].frequency #=> false
    [:a, :b].frequency == [:b, :a].frequency #=> true
    

提交回复
热议问题