Ruby:遍历两个哈希数组并创建数组数组

Ruby: iterate over two array of hashes and create array of arrays

我有两个哈希数组

  1. rtgid, position_id, valid_from, valid_to
  2. invid, 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}]

我需要用 rtginv 散列中的 id 对创建数组数组,其中

1) position_id 匹配和

2) 来自 invdate 与来自 rtg

valid_fromvalid_to 的愤怒

请问我该怎么做?

在我上面的例子中,结果是: result = [[7,23],[6,17]]

试试这个

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

希望对您有所帮助

您可以使用嵌套 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]]