s c s c - 1 year ago 59
Ruby Question

compare array of hashes and print expected & actual results

I have 2 array of hashes:

actual = [{"column_name"=>"NONINTERESTINCOME", "column_data_type"=>"NUMBER"},
{"column_name"=>"NONINTERESTEXPENSE", "column_data_type"=>"VARCHAR"},
{"column_name"=>"TRANSACTIONDATE", "column_data_type"=>"TIMESTAMP"},
{"column_name"=>"UPDATEDATE", "column_data_type"=>"TIMESTAMP"}]
expected = [{"column_name"=>"NONINTERESTINCOME", "column_data_type"=>"NUMBER"},
{"column_name"=>"NONINTERESTEXPENSE", "column_data_type"=>"NUMBER"},
{"column_name"=>"TRANSACTIONDATE", "column_data_type"=>"NUMBER"},
{"column_name"=>"UPDATEDATE", "column_data_type"=>"TIMESTAMP"}]

I need to compare these 2 hashes and find out the ones for which the

to compare we can directly use:

diff = actual - expected

This will print the output as:

{"column_name"=>"NONINTERESTEXPENSE", "column_data_type"=>"VARCHAR"}
{"column_name"=>"TRANSACTIONDATE", "column_data_type"=>"TIMESTAMP"}

My expected output is that in the result i want to print the actual and expected datatype, means the datatypes for the missing `column_name' from both the actual and expected array of hashes, something like:

{"column_name"=>"NONINTERESTEXPENSE", "expected_column_data_type"=>"NUMBER", "actual_column_data_type" => "VARCHAR"}
{"column_name"=>"TRANSACTIONDATE", "expected_column_data_type"=>"NUMBER","actual_column_data_type" => "TIMESTAMP" }

ndn ndn
Answer Source
(expected - actual).
  concat(actual - expected).
  group_by { |column| column['column_name'] }.
  map do |name, (expected, actual)|
      'column_name'               => name,
      'expected_column_data_type' => expected['column_data_type'],
      'actual_column_data_type'   => actual['column_data_type'],
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download