Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if hash contains any empty values

I have the following hash and I'm looking for an easy way to check if everything is empty in the hash. Not all values are always visible in the hash so sometimes the hash is without end_date / start_date or anything else.

test
=> {"0"=>
  {"_destroy"=>"",
   "START_DATE"=>"",
   "END_DATE"=>"",
   "EMPLOYER"=>"",
   "JOB_TITEL"=>"",
   "FUNCTIONAL_AREA"=>"",
   "INDUSTRY"=>"",
   "DESCRIPTION_TXT"=>"",
   "COUNTRY"=>"",
   "CITY"=>"",
   "REGION"=>"",
   "CONTRACT_TYPE"=>""},
 "1"=>
  {"_destroy"=>"",
   "START_DATE"=>"",
   "END_DATE"=>"",
   "EMPLOYER"=>"",
   "JOB_TITEL"=>"",
   "FUNCTIONAL_AREA"=>"",
   "INDUSTRY"=>"",
   "DESCRIPTION_TXT"=>"",
   "COUNTRY"=>"",
   "CITY"=>"",
   "REGION"=>"",
   "CONTRACT_TYPE"=>""},
 "2"=>
  {"_destroy"=>"",
   "START_DATE"=>"",
   "END_DATE"=>"",
   "EMPLOYER"=>"",
   "JOB_TITEL"=>"",
   "FUNCTIONAL_AREA"=>"",
   "INDUSTRY"=>"",
   "DESCRIPTION_TXT"=>"",
   "COUNTRY"=>"",
   "CITY"=>"",
   "REGION"=>"",
   "CONTRACT_TYPE"=>""}}

In pseudocode it would like this

Start loop
-> check if current position contains an empties 
=> if all is empty delete position
-> continue
end loop

In this example it means that the hash will be empty at the end of the loop.

Kind regards

like image 568
FastSolutions Avatar asked Mar 04 '14 19:03

FastSolutions


1 Answers

Use Hash#delete_if:

test.delete_if { |i,h| h.all? { |k,v| v.empty? } }
like image 104
Matt Avatar answered Oct 04 '22 20:10

Matt