0

I have this hash:

{
  a: [
    { b: 'c' },
    { d: 'e' }
  ],
  b: [
    { f: 'f' },
    { g: 'g' }
  ]
}

How can I test it that it's contents are equal to another to another hash without considering the order of the keys? For example:

{
  b: [
    { g: 'g' },
    { f: 'f' }
  ]
  a: [
    { d: 'e' },
    { b: 'c' }
  ]
}

As you can see both are hashes identical for my purposes, except for the order of keys in the shallow and nested positions.

I tried this, but it fails because it takes into account the key order:

test 'hashes have same content' do
  assert_equal expected_hash, result_hash
end
Jumbalaya Wanton
  • 1,601
  • 1
  • 25
  • 47
  • It really required to know, the *equality test factors*... – Arup Rakshit May 28 '14 at 16:51
  • @ArupRakshit I clarified my question. I want to ascertain the hash contents are equal without considering the order. – Jumbalaya Wanton May 28 '14 at 16:53
  • Use this http://ruby-doc.org/stdlib-2.1.1/libdoc/test/unit/rdoc/Test/Unit/Assertions.html#method-i-assert_equal also good to see this [blog](http://ruby.about.com/od/testdrivendevelopment/ss/Unit-Testing-With-Minitest-More-Assertions.htm) – Arup Rakshit May 28 '14 at 16:56
  • @p11y I don't think what you provided is a possible duplicate. I want to compare that two hashes have the same keys in any order. Not get the difference between the two hashes. – Jumbalaya Wanton May 28 '14 at 17:04
  • @ArupRakshit I'm using Rails. – Jumbalaya Wanton May 28 '14 at 17:05
  • 2
    I believe your problem is not with the hash keys, but rather with the hash _values_, which are arrays, and they are order-sensitive by default – Uri Agassi May 28 '14 at 17:07
  • You write a method for equality test of 2 hash as per the dup question link, then use the method [`assert`](http://ruby-doc.org/stdlib-2.1.1/libdoc/test/unit/rdoc/Test/Unit/Assertions.html#method-i-assert) only by passing the your method name as a symbol. – Arup Rakshit May 28 '14 at 17:12

0 Answers0