从Ruby中的哈希数组中删除哈希

时间:2013-10-07 06:21:02

标签: ruby arrays hash

我有一系列哈希如下:

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

现在,我想首先检查数组是否包含值为"k1"的键"v3"的哈希值。如果是,那么我想从数组中删除该哈希。

结果应为:

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

2 个答案:

答案 0 :(得分:40)

使用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-"}]

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

答案 1 :(得分:12)

您可以使用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-"}]