Wednesday, June 24, 2015

How to delete nested hash elements based on the elements properties

data = {
"total_records"=>3,
"records"=>
   [{"title"=>"Val1",
   "coins"=>1},
   {"title"=>"Val2",
   "coins"=>1},
   {"title"=>"Val3",
   "coins"=>1}]
}

p data

data['records'].delete_if{ |h| %w(Val1 Val2).include?(h['title']) }

p data

Output:

{"total_records"=>3, "records"=>[{"title"=>"Val1", "coins"=>1}, {"title"=>"Val2", "coins"=>1}, {"title"=>"Val3", "coins"=>1}]}
{"total_records"=>3, "records"=>[{"title"=>"Val3", "coins"=>1}]}