gpt4 book ai didi

arrays - 哈希数组之间的交集,但返回完整的哈希

转载 作者:行者123 更新时间:2023-12-03 23:59:29 24 4
gpt4 key购买 nike

有两个哈希数组

actual = [{id: 1, text: "A", type: "X", state: "enabled"}, {id: 2, text: "B", type: "X", state: "enabled"}]

expected = [{text: "A", type: "X", state: "enabled"}]

我需要获取“预期”中未包含的所有哈希的 :id。必须使用三个键(文本、类型、状态)进行比较。在这种情况下

results = [{id: 2}]

目前我正在使用它,但它很长并且不适用于大型阵列。有没有更好的办法?

 actuals        = actuals.map{|a| a.slice(:text, :type, :state)}
expected = expected.map{|a| a.slice(:text, :type, :state)}
not_expected = actuals - expected

results = actuals.select{|actual|
not_expected.find{|n|
n[:text] == actual[:text] &&
n[:type] == actual[:type] &&
n[:state] == actual[:state]
}.present?
}

最佳答案

actual = [{id: 1, text: "A", type: "X", state: "enabled"}, {id: 2, text: "B", type: "X", state: "enabled"}]
expected = [{text: "A", type: "X", state: "enabled"}]
comparable_expected = expected.map { |e| e.slice(:text, :type, :state) }

results = actual.select do |a|
not comparable_expected.include? a.slice(:text, :type, :state)
end

resulting_ids = results.map(&:id)

关于arrays - 哈希数组之间的交集,但返回完整的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63636364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com