Reputation: 14664
I am having two structures similar to the one below.
[1 => [{'pc'=>1,'id'=>0},{'pc'=>4,'id'=>0},{'pc'=>2,'id'=>1]]
But both of them need not contain the inside array in the exact same order. How to compare in such case?
Upvotes: 0
Views: 516
Reputation: 81
If both the nested hashes having same keys & order, we can write a recursive method to do the comparison. I am not sure whether we have inbuilt method to do so.
Upvotes: 0
Reputation: 94
It seems a simple compare works:
data = {
1 => [{'pc'=>1,'id'=>0},{'pc'=>4,'id'=>0},{'pc'=>2,'id'=>1}],
2 => [{'pc'=>1,'id'=>0},{'pc'=>4,'id'=>0},{'pc'=>2,'id'=>1}],
3 => [{'pc'=>1,'id'=>0},{'pc'=>2,'id'=>1},{'pc'=>4,'id'=>0}]
}
data[1] == data[2]
#> true
data[2] == data[3]
#> false
Upvotes: 0
Reputation: 44080
If the order isn't important, you should consider other structures instead of Array there, Set
, for example.
You can use Set for comparing as well, by converting Arrays to Sets before comparison:
require 'set'
a = [{:a => 2}, {:b => 3}]
b = [{:b => 3}, {:a => 2}]
sa = Set.new a
#=> #<Set: {{:a=>2}, {:b=>3}}>
sb = Set.new b
#=> #<Set: {{:b=>3}, {:a=>2}}>
a == b
#=> false
sa == sb
#=> true
Upvotes: 1