Search code examples
rubyhashhashmapnested-attributesruby-on-rails-2

Difference between 2 different nested hash in Ruby 1.8.7


Consider the Following nested Hash:

data1 = {
  "3"=>{"passenger_type"=>"ADT", "the_order"=>"3", "last"=>"JONES", "first"=>"ALENA", "middle"=>nil}, 
  "2"=>{"passenger_type"=>"ADT", "the_order"=>"2", "last"=>"JONES", "first"=>"MAXIM", "middle"=>nil}, 
  "1"=>{"passenger_type"=>"ADTT", "the_order"=>"1", "last"=>"JONES", "first"=>"TODD", "middle"=>nil}}


data2 = {
   "3"=>{"first"=>"ALENA", "the_order"=>"3", "middle"=>"", "passenger_type"=>"ADTT", "last"=>"JONES"}, 
   "2"=>{"first"=>"MAXIM", "the_order"=>"2", "middle"=>"", "passenger_type"=>"ADT", "last"=>"JONES"}, 
   "1"=>{"first"=>"TODD", "the_order"=>"1", "middle"=>"", "passenger_type"=>"ADT", "last"=>"JONESS"}}

The Output Should be like this(difference between both hash listed values):

{"3" => {"passenger_type" => ["ADT", "ADTT"]}, 
 "1" => {"passenger_type" => ["ADTT", "ADT"], "last" => ["JONES", "JONESS"]}

Anyone your suggestion is appreciated, thanks in advance.


Solution

  • You can use the form of Hash#merge that takes a block to produce the desired result in a compact manner:

    data1.merge(data2) { |_,ho,hn|
           ho.merge(hn) { |_,o,n| (o==n||o==''||n=='') ? nil : [o,n] }
             .delete_if { |_,v| v==nil } }
         .delete_if { |_,v| v.empty? }
      #=> {"3"=>{"passenger_type"=>["ADT", "ADTT"]},
      #    "1"=>{"passenger_type"=>["ADTT", "ADT"], "last"=>["JONES", "JONESS"]}}