简体   繁体   中英

Delete data from an array within a hash within an array - Ruby

I have a array say my_array which has data as below:

[
    {
        : 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. 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:

[
    {
        : 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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