简体   繁体   English

从数组中的散列内的数组中删除数据 - Ruby

[英]Delete data from an array within a hash within an array - Ruby

I have a array say my_array which has data as below: 我有一个数组说my_array,其数据如下:

[
    {
        : name=>"Orange",
        : data=>[
            [
                1421215199000,
                0
            ],
            [
                1421215199000,
                2.2566121687633
            ],
            [
                1421819999000,
                0
            ],
            [
                1421819999000,
                2.43260664893362
            ],
            [
                1422424799000,
                0
            ],
            [
                1422424799000,
                0
            ]
        ]
    },
    {
        : name=>"Apple",
        : data=>[

        ]
    },
    {
        : name=>"Mango",
        : data=>[

        ]
    }
]

From the values/array for ":data", I wish to remove the array objects having '0' as the value. 从“:data”的values / array中,我希望删除值为“0”的数组对象。 As in this example, I wish the following items to be removed: 在此示例中,我希望删除以下项目:

[
    1421215199000,
    0
],

[
    1421819999000,
    0
],
[
    1422424799000,
    0
],
[
    1422424799000,
    0
]

So the final my_array after removing the items mentioned above, should look like: 因此,删除上述项目后的最终my_array应如下所示:

[
    {
        : name=>"Orange",
        : data=>[
            [
                1421215199000,
                2.2566121687633
            ],
            [
                1421819999000,
                2.43260664893362
            ]
        ]
    },
    {
        : name=>"Apple",
        : data=>[

        ]
    },
    {
        : name=>"Mango",
        : data=>[

        ]
    }
]

Is there an easy way to achieve this in ruby? 有没有一种简单的方法来实现红宝石?

#!/usr/bin/env ruby
require 'pp'

f = [
    {
        :name=>"Orange",
        :data=>[
            [
                1421215199000,
                0
            ],
            [
                1421215199000,
                2.2566121687633
            ],
            [
                1421819999000,
                0
            ],
            [
                1421819999000,
                2.43260664893362
            ],
            [
                1422424799000,
                0
            ],
            [
                1422424799000,
                0
            ]
        ]
    }]

tp = f.collect{|x| x.merge(:data => x[:data].reject{|p| p[1]==0}) }
pp tp

the collect does all the magic. 收集所有的魔力。

The way to read it is: for each element of the array, a hash, replace the value associated with the data key with the value generated by going over the data key and rejecting all elements that have the 2nd item in the array equal to 0. 读取它的方法是:对于数组的每个元素,使用散列,将数据键关联的值替换为通过遍历数据键生成的值,并拒绝数组中第2项等于0的所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM