简体   繁体   中英

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

I have two arrays of hashes

  1. rtg with keys id, position_id, valid_from, valid_to
  2. inv with keys id, position_id, date

Examples look like this:

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

I need to create array of arrays with id pairs from rtg and inv hashes where

1) position_id match and

2) date from inv is in rage of valid_from & valid_to from rtg

How do I do this, please?

In my example above result would be: result = [[7,23],[6,17]]

Try this

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

Hope this helps

You could use nested each to compare each item in both arrays, grabbing the id s for those items that match the conditions; for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM