0

我正在尝试将一个哈希值与每个键的另一个哈希值进行比较。像下面一样

db_data = [{"user_id"=>"000879", "dept"=>"1066", "type"=>"A", "rate"=>"999"},
          {"user_id"=>"000879", "dept"=>"1066","type"=>"AB", "rate"=>"999"},
          {"user_id"=>"008118", "dept"=>"10000869", "type"=>"A", "rate"=>"950"}]

file_data = [{"user"=>"00094967",  "dept_id"=>"0020",  "price"=>950, "div_type"=>"A"},
            {"user"=>"00094967", "dept_id"=>"0020",  "price"=>950, "div_type"=>"A"},
            {"user"=>"00094967",  "dept_id"=>"0020", "price"=>950, "div_type"=>"AB"}]

我需要比较第一个哈希数据中的特定值键,以与每个哈希值的第二个特定键值进行比较。就像从dept_idfile_data 与 db_data 比较所有键值dept,如果没有得到则存储在变量中(不同的数据存储)

4

2 回答 2

0
results = []
existed = false
file_data.each do |fd|
  dept_id = fd['dept_id']
  db_data.each do |dd|
    if dept_id == dd['dept']
      existed = true
      break
    end
  end
  results << fd if existed == false

  existed = false
end

# {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"A"}
# {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"A"}
# {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"AB"}
# because dept_id 0020 is not existed in db_data, so it will go to result

因此,如果 db_data 的第一个循环中存在 dept_id ,它将不会将数据存储到结果中。如果直到 db_data 的最后一个元素不存在,那么它将转到结果。然后存在的标志将再次重置为false。

也许这不是rubyist方式,但它会做

于 2021-01-29T12:12:11.887 回答
0

如果我明白了,你可以使用Array#select

file_data.select { |h| !db_data.map { |hh| hh['dept'] }.include? h['dept_id'] }

wheredb_data.map { |hh| hh['dept'] }是一个包含 key 值的数组'dept'

于 2021-01-29T13:33:24.003 回答