【问题标题】:Reject hash from array of hashes based on a condition in ruby根据 ruby​​ 中的条件从哈希数组中拒绝哈希
【发布时间】:2021-08-23 03:27:13
【问题描述】:

我有一个如下所示的哈希数组。

[
   {
      "name":"keith",
      "age":"20",
      "weight":"100lb",
      "status":"CURRENT"
   },
   {
      "name":"keith",
      "age":"20",
      "weight":"110lb",
      "status":"PREVIOUS"
   },
   {
      "name":"keith",
      "age":"20",
      "weight":"120lb",
      "status":"FUTURE"
   }
]

我正在尝试根据以下条件删除哈希:如果 nameage 相同,则取出具有 status CURRENT 的哈希,忽略其他状态 PREVIOUS 和 FUTURE。所以输出应该是

[
   {
      "name":"keith",
      "age":"20",
      "weight":"100lb",
      "status":"CURRENT"
   }
]

我曾尝试使用group_byflat_map,但无法获得所需的输出。 有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    尝试以下方法:

    arr.uniq { |h| [h[:name], h[:age]] }.select { |h| h[:status] == 'CURRENT' }
    

    【讨论】:

    • 非常感谢您的回复。这行得通。但对不起,我忘了在问题中提到另一个条件。也就是说,如果有 2 个哈希值,一个状态为 FUTURE,另一个状态为 PREVIOUS,那么它应该返回两个哈希值只有当状态设置为 CURRENT 的哈希值时,其他所有哈希值都应该被忽略
    • 所以我使用arr.group_by {|h| "#{h['name']}_#{h['age']}"}.values.flatten.select{|h| h['status'] == 'CURRENT'} 有什么有效的方法吗?
    • 我无法理解这个要求。你能给我举个例子吗?
    【解决方案2】:

    据我了解问题(包括在 cmets 中添加的上下文),任务如下:

    • 对于(姓名、年龄)的任意组合,如果我们有一个具有status == CURRENT 的条目,我们应该只返回这个条目
    • 否则,我们应该按原样返回原始条目

    例如,对于数据

    data = [
      {
        "name":"keith",
        "age":"20",
        "weight":"100lb",
        "status":"CURRENT"
      },
      {
        "name":"keith",
        "age":"20",
        "weight":"110lb",
        "status":"PREVIOUS"
      },
      {
        "name":"keith",
        "age":"20",
        "weight":"120lb",
        "status":"FUTURE"
      },
      {
        "name":"alice",
        "age":"20",
        "weight":"120lb",
        "status":"PREVIOUS"
      },
      {
        "name":"alice",
        "age":"20",
        "weight":"120lb",
        "status":"FUTURE"
      },
    ]
    

    上述操作的结果应该是

    [
      {:name=>"keith", :age=>"20", :weight=>"100lb", :status=>"CURRENT"},
      {:name=>"alice", :age=>"20", :weight=>"120lb", :status=>"PREVIOUS"},
      {:name=>"alice", :age=>"20", :weight=>"120lb", :status=>"FUTURE"}
    ]
    
    

    (所以对于 (keith, 20) 我们只返回一个哈希,其中状态 == CURRENT,对于 (alive, 不管) 我们返回初始数据不变)。

    解决方案似乎很简单:

    1. 按(姓名、年龄)分组
    2. 对于每个组,如果它包含一个状态 == CURRENT 的条目(哈希),则只返回此条目,否则按原样返回整个组。

    在 Ruby 中也一样:

    data
      .group_by { |name:, age:, **| [name, age] }
      .reduce([]) do |acc, (_, group)|
        current = group.find { |status:, **| status == "CURRENT" }    
        current ? acc.push(current) : acc.concat(group)
      end
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多