我有两个哈希数组
rtg
,密钥为id, position_id, valid_from, valid_to
inv
,密钥为id, position_id, date
示例如下:
rtg=[{:id=>7, :position_id=>3, :valid_from=>Tue, 05 Sep 2017 10:00:00 EEST +03:00, :valid_to=>Tue, 05 Sep 2017 10:59:59 EEST +03:00},
{:id=>6, :position_id=>3, :valid_from=>Mon, 04 Sep 2017 22:00:00 EEST +03:00, :valid_to=>Mon, 04 Sep 2017 23:59:59 EEST +03:00},
{:id=>1, :position_id=>2, :valid_from=>Mon, 04 Sep 2017 07:00:00 EEST +03:00, :valid_to=>Mon, 04 Sep 2017 08:00:00 EEST +03:00}]
inv=[{:id=>23, :position_id=>3, :date=>Tue, 05 Sep 2017 10:10:00 EEST +03:00},
{:id=>17, :position_id=>3, :date=>Mon, 04 Sep 2017 22:45:00 EEST +03:00},
{:id=>11, :position_id=>3, :date=>Mon, 04 Sep 2017 07:20:00 EEST +03:00}]
我需要创建id
和rtg
哈希值inv
对的数组数组
1)position_id
匹配和
2)来自date
的{{1}}风靡inv
&来自valid_from
valid_to
我该怎么办?
在上面的例子中,结果将是:
rtg
答案 0 :(得分:1)
试试这个
array = []
rtg.each do |record|
matched_record = inv.find { |inventory| inventory[:position_id] == record[:position_id] && inventory[:date].to_i.in?(record[:valid_from].to_i..record[:valid_to].to_i) }
array << [record.id, matched_record.id] if matched_record
end
希望这有帮助
答案 1 :(得分:1)
您可以使用嵌套的each
来比较两个数组中的每个项目,为那些符合条件的项目抓取id
;例如:
rtg.each_with_object([]) do |r, result|
inv.each do |i|
if i[:position_id] == r[:position_id] && i[:date].between?(r[:valid_from], r[:valid_to])
result << [r[:id], i[:id]]
end
end
end
#=> [[7, 23], [6, 17]]