检查哈希是否包含任何空值

时间:2014-03-04 19:37:59

标签: ruby-on-rails ruby loops hash

我有以下哈希,我正在寻找一种简单的方法来检查哈希中是否所有内容都是空的。并非所有值都始终在哈希值中可见,因此有时哈希没有end_date / start_date或其他任何值。

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"=>""}}

在伪代码中它想要这个

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

在此示例中,这意味着在循环结束时哈希将为空。

亲切的问候

1 个答案:

答案 0 :(得分:4)

使用Hash#delete_if

test.delete_if { |i,h| h.all? { |k,v| v.empty? } }