ruby迭代并在分组后删除

时间:2013-07-02 12:22:52

标签: ruby

我有一个简单的数组:

[
    [0] {
        "user_id" => 4,
           "type" => 1
    },
    [1] {
        "user_id" => 4,
           "type" => 1
    },
    [2] {
        "user_id" => 1,
           "type" => 1
    },
    [3] {
        "user_id" => 2,
           "type" => 65
    },
    [4] {
        "user_id" => 1,
           "type" => 23
    },
    [5] {
        "user_id" => 4,
           "type" => 4
    }
]

我想要做的就是删除具有相同user_id和类型的元素,然后将它们组合在一起并将它们放回到数组中。所以结果就是这种情况:

[
    [0] {
        "user_id" => 1,
           "type" => 1
    },
    [1] {
        "user_id" => 2,
           "type" => 65
    },
    [2] {
        "user_id" => 1,
           "type" => 23
    },
    [3] {
        "user_id" => 4,
           "type" => 4
    },
    [4] [
        [0] {
            "user_id" => 4,
               "type" => 1
        },
        [1] {
            "user_id" => 4,
               "type" => 1
        }
    ]
]

是否有一种简单的方法可以执行此操作,还是必须手动迭代并执行此操作?感谢

1 个答案:

答案 0 :(得分:2)

require 'pp'
a = [
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 1,
           "type" => 1
    },
    {
        "user_id" => 2,
           "type" => 65
    },
    {
        "user_id" => 1,
           "type" => 23
    },
    {
        "user_id" => 4,
           "type" => 4
    }
]

pp a.group_by{|i| i.values_at("user_id","type") }.values

output:

[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
 [{"user_id"=>1, "type"=>1}],
 [{"user_id"=>2, "type"=>65}],
 [{"user_id"=>1, "type"=>23}],
 [{"user_id"=>4, "type"=>4}]]

<强>更新

require 'pp'
a = [
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 4,
           "type" => 1
    },
     {
        "user_id" => 1,
           "type" => 1
    },
    {
        "user_id" => 2,
           "type" => 65
    },
    {
        "user_id" => 1,
           "type" => 23
    },
    {
        "user_id" => 4,
           "type" => 4
    }
]

arr = a.map do |i|
  tot = a.count(i)
  next ([i] * tot) if tot > 1 ; i
end.uniq
pp arr

输出:

[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
 {"user_id"=>1, "type"=>1},
 {"user_id"=>2, "type"=>65},
 {"user_id"=>1, "type"=>23},
 {"user_id"=>4, "type"=>4}]