Boolean
Boolean

Reputation: 14664

Comparing hash of hashes in Ruby

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

Answers (3)

spgokul
spgokul

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

Marcus Derencius
Marcus Derencius

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

Mladen Jablanović
Mladen Jablanović

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

Related Questions