ruby:如果数组中一个键的值为0,如何删除哈希?

时间:2014-10-08 09:49:26

标签: ruby arrays hash

例如,我有一个这样的数组:

array = [{"a"=>0, "b"=>1, "c"=>2}, {"a"=>2, "b"=>1, "c"=>0}, {"a"=>3, "b"=>1, "c"=>2}]

现在我要删除"a" == 0项,返回:

array = [{"a"=>2, "b"=>1, "c"=>0}, {"a"=>3, "b"=>1, "c"=>2}]

怎么办?

3 个答案:

答案 0 :(得分:2)

使用Array#reject

array.reject { |h| h["a"] == 0 }
#=> [{"a"=>2, "b"=>1, "c"=>0}, {"a"=>3, "b"=>1, "c"=>2}]

答案 1 :(得分:2)

array.collect {|k| k unless k["a"] == 0}.compact  

答案 2 :(得分:1)

您也可以使用Array#delete_if

array.delete_if {|h| h["a"] == 0}