根据其他哈希数组的键值更新一个哈希数组

时间:2018-11-29 12:44:18

标签: ruby-on-rails ruby

我有以下两个哈希数组。我正试图从不在其Patient_and_doctor哈希数组的doctor_ Patient_id数组中不存在Doctor_ Patient_id的Doctor数组哈希中删除该记录。

doctor = [
  { :doctor_patient_id=>"abc",
    :doctor_id=>"d1"
  },
  { :doctor_patient_id=>"def",
    :doctor_id=>"d2"
  },
  { :doctor_patient_id=>"ghi",
    :doctor_id=>"d3"
  }
]

patient_and_doctor = [
  { :patient_id=>"11e8f37477ab7028a66b210b9699def9",
    :doctor_patient_id=>[ "def", "zkj", "cps" ]
  },
  { :patient_id=>"11e8f37481fabfe68630f5da2e22dceb",
    :doctor_patient_id=>[ "uio", "ghi", "jkk" ]
  }
]

预期输出为:

doctor = [
      { :doctor_patient_id=>"def",
        :doctor_id=>”d2”
      },
      { :doctor_patient_id=>"ghi",
        :doctor_id=>”d3”
      }
    ]

我试图做以下类似的事情,但是没有运气,

patient_and_doctor.each do |dp|
  data = doctor.map {|d| d[:doctor_patient_id].include? 
   dp[:doctor_patient_id] }
end

我该如何实现?

2 个答案:

答案 0 :(得分:4)

valid_ids = patient_and_doctor.flat_map { |h| h[:doctor_patient_id] }
# => ["def", "zkj", "cps", "uio", "ghi", "jkk"]

doctor.select { |h| valid_ids.include? h[:doctor_patient_id] }
# => [{:doctor_patient_id=>"def", :doctor_id=>"d2"},
#     {:doctor_patient_id=>"ghi", :doctor_id=>"d3"}]

如果您希望更改select!数组而不是返回新数组,请使用select而不是doctor

答案 1 :(得分:1)

以下内容可获得必填答案,

doctor.select { |x|  patient_and_doctor.map { |x| x[:doctor_patient_id] }.flatten.include?(x[:doctor_patient_id]) }