在一次迭代中计算数组对象类型

Count array object types in one iteration

我有一个 JSON 格式

{body => ["type"=>"user"...], ["type"=>"admin"...]}

我想按类型对对象进行计数,但我不想将数组迭代三次(那是我有多少个不同的对象),所以这行不通:

  @user_count = json["body"].count{|a| a['type'] == "user"}
  @admin_count = json["body"].count{|a| a['type'] == "admin"}
  ...

有没有不使用 .each 块和使用 if 语句来计算对象类型的聪明方法?

您可以使用 each_with_object 创建具有 type => count 对的散列:

json['body'].each_with_object(Hash.new(0)) { |a, h| h[a['type']] += 1 }
#=> {"user"=>5, "admin"=>7, ...}

您可以使用 each:

将计数存储到散列中
counts = { "user" => 0, "admin" => 0, "whatever" => 0 }
json["body"].each do |a|
  counts[a.type] += 1
end

counts["user"] #=> 1
counts["admin"] #=> 2
counts["whatever"] #=> 3