Deleting a hash from array of hashes in Ruby

后端 未结 2 2002
南方客
南方客 2020-12-30 04:08

I have an array of hashes as following:

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


        
相关标签:
2条回答
  • 2020-12-30 04:24

    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.

    0 讨论(0)
  • 2020-12-30 04:30

    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-"}]
    
    0 讨论(0)
提交回复
热议问题