获取没有空值的哈希长度

时间:2014-09-24 13:19:45

标签: ruby arrays ruby-on-rails-4

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

filters.length4,但我想获得2(不仅拥有密钥,还拥有价值的人)

4 个答案:

答案 0 :(得分:5)

使用count

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

filters.count { |k, v| v.present? }
#=> 2

答案 1 :(得分:0)

您可以使用

filters.reject { |k, v| v.empty? }.length # => 2

答案 2 :(得分:0)

解析json字符串。

require 'json'

json_string = <<EOS
{
  "filters": {
    "start_year": "2009",
    "end_year": "2011",
    "theme": "",
    "discipline": ""
  }
}
EOS

h = JSON.parse(json_string)

使用Enumerable#select过滤值:

h['filters'].values.select { |x| x != "" }
# => ["2009", "2011"]
h['filters'].values.select { |x| x != "" }.size
# => 2

答案 3 :(得分:0)

filters.values.reject(&:empty?).length

如果您将空值保存为nil而不是'',则可以使用:

filters.values.compact.length