Deleting a hash from array of hashes in Ruby

2020-02-25 08:22发布

I have an array of hashes as following:

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

Now, I want to first check whether the array contains a hash with key "k1" with value "v3". If yes, then I want to delete that hash from the array.

The result should be:

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

标签: ruby arrays hash
2条回答
狗以群分
2楼-- · 2020-02-25 08:42

You can do this with Array#reject(If you don't want to modify the receiver) and also with Array#reject!(If you want to modify the receiver)

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-"}]
查看更多
叛逆
3楼-- · 2020-02-25 08:52

Use 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-"}]

If there is no hash matching the condition, the array is left unchanged.

查看更多
登录 后发表回答