Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 哈希数组之间的交集,但返回完整哈希_Arrays_Ruby On Rails_Ruby_Hash - Fatal编程技术网

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

Arrays 哈希数组之间的交集,但返回完整哈希,arrays,ruby-on-rails,ruby,hash,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: "enabl

有两个哈希数组

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

如果与
exp
合并时,
actual
中的哈希值不受影响,则会被拒绝,这意味着要合并的哈希值对于
exp
中的所有键都具有相同的值。然后,使用将
actual
中的每个剩余哈希
h
映射到
{id:h[:id]}

这种方法的一个优点是,如果
exp
更改为具有不同密钥的散列,则不需要更改代码

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)
exp = expected.first
  #=> {text: "A", type: "X", state: "enabled"}

actual.reject { |h| h == h.merge(exp) }.map { |h| h.slice(:id) }
  #=> [{:id=>2}]