Removing a hash from a hash array in Ruby
I have an array of hashes as shown below:
[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}] Now I want to first check if the array contains a hash with the key "k1" with the value "v3" . If so, then I want to remove this hash from the array.
The result should be:
[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}] 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 the hash does not match the condition, the array remains unchanged.
You can do this with Array#reject (if you do not want to change the receiver) as well as Array#reject! (if you want to change 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-"}]