获取没有空值的哈希长度

Pau*_*aul -2 ruby arrays ruby-on-rails-4

filters = {
  "start_year" => "2009",
  "end_year" => "2011",
  "theme" => "",
  "discipline" => ""
}
Run Code Online (Sandbox Code Playgroud)

filters.length是的4,但我想得到2(那些不仅有钥匙,还有价值的人)

Ste*_*fan 5

用途count:

filters = {"start_year"=>"2009", "end_year"=>"2011", "theme"=>"", "discipline"=>""}

filters.count { |k, v| v.present? }
#=> 2
Run Code Online (Sandbox Code Playgroud)