【问题标题】:Intersection between array of hashes but returning the full hash哈希数组之间的交集,但返回完整的哈希
【发布时间】:2020-12-17 12:57:44
【问题描述】:

有两个哈希数组

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

【问题讨论】:

    标签: arrays ruby-on-rails ruby hash


    【解决方案1】:
    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)
    

    【讨论】:

      【解决方案2】:
      exp = expected.first
        #=> {text: "A", type: "X", state: "enabled"}
      
      actual.reject { |h| h == h.merge(exp) }.map { |h| h.slice(:id) }
        #=> [{:id=>2}]
      

      Try it

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

      这种方法的一个优点是,如果将exp 更改为具有不同键的哈希,则无需更改代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-30
        • 2014-11-14
        • 2021-05-09
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-03
        相关资源
        最近更新 更多