"NONINTERESTINCOME", "column_data_type"=>"NUMBER"}, {"column_-6ren">
gpt4 book ai didi

ruby - 比较哈希数组并打印预期和实际结果

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:12 24 4
gpt4 key购买 nike

我有 2 个哈希数组:

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"}]

我需要比较这 2 个哈希并找出 column_data_type 不同的那些。

比较我们可以直接使用:

diff = actual -   expected

这会将输出打印为:

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

我的预期输出是在结果中我想打印实际和预期的数据类型,这意味着实际和预期的哈希数组中缺失的“column_name”的数据类型,例如:

{"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" }

最佳答案

无论数组中散列的顺序如何,这都会起作用。

diff = []

expected.each do |elem|
column_name = elem['column_name']
column_type = elem['column_data_type']
match = actual.detect { |elem2| elem2['column_name'] == column_name }
if column_type != match['column_data_type']
diff << { 'column_name' => column_name,
'expected_column_data_type' => column_type,
'actual_column_data_type' => match['column_data_type'] }
end
end

p diff

关于ruby - 比较哈希数组并打印预期和实际结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40528021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com