Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two hash arrays in ruby except a key

Tags:

ruby

hash

I have two hash arrays like this:

hashArray1 = [{"id"=>"1","data"=>"data1"},{"id"=>"2","data"=>"data2"}]
hashArray2 = [{"id"=>"3","data"=>"data1"},{"id"=>"4","data"=>"data2"}]

I want to compare both of them and return true if everything else matches without the "id" key.

I have tried something like this:

hashArray1.each do |h1|
  hashArray2.each do |h2|
    if h1.select{|h| h!= "id"} == h2.select{|b| b!= "id"}
      break
    else
      return false
    end
  end
end

But this seems to be incorrect. Does anyone have a better solution. I am on plain ruby 1.9.3, not using rails framework.

like image 668
Infant Dev Avatar asked Sep 11 '26 23:09

Infant Dev


1 Answers

I would simply do:

hash1.zip(hash2).all? do |h1,h2|
  return false unless h1.keys == h1.keys
  h1.keys.each do |key|
      return false if h1[key] != h2[key] unless key == 'id'
  end
end
like image 52
hirolau Avatar answered Sep 13 '26 15:09

hirolau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!