19

我有一个哈希数组,如下所示:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]

现在,我想首先检查数组是否包含带有 key"k1"和 value的散列"v3"。如果是,那么我想从数组中删除该哈希。

结果应该是:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]
4

2 回答 2

58

使用Array#delete_if

arr = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]

arr.delete_if { |h| h["k1"] == "v3" }
#=> [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]

如果没有匹配条件的哈希,则数组保持不变。

于 2013-10-07T06:23:50.843 回答
15

您可以使用Array#reject(如果您不想修改接收器)和Array#reject!(如果您想修改接收器)来执行此操作

arr = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
p arr.reject { |h| h["k1"] == "v3" }
# >> [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]    

arr = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
p arr.reject! { |h| h["k1"] == "v3" }
# >> [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]
于 2013-10-07T06:28:13.010 回答