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

标签 arrays ruby-on-rails ruby hash

有两个哈希数组

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/

相关文章:

c# - C#中的常量数组

javascript - 如何将此类对象的此类数组传递给 JS?

ruby-on-rails - 如何遍历哈希列表?

ruby-on-rails - Vue.js 在 if 评估后清除数据

ruby-on-rails - OS X El Capitan - 无法使用 gem 安装 bundler

ruby - `File::exist?` 和 `File::exists?` 之间的区别

python - 将 2D 和 1D 数组相乘以获得 3D 数组

javascript - JavaScript 中的 "Look and say sequence"

哈希上的 Ruby case 语句?

arrays - 将 Ruby 数组元素传递给方法