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

时间:2015-07-06 09:56:23

标签: ruby ruby-on-rails-3

我有一个格式为

的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语句的情况下计算对象类型?

2 个答案:

答案 0 :(得分:4)

您可以使用each_with_object创建一个json['body'].each_with_object(Hash.new(0)) { |a, h| h[a['type']] += 1 } #=> {"user"=>5, "admin"=>7, ...} 对的哈希:

TSMessage.showNotificationWithTitle("Success Notification !!!", type: .Success)

答案 1 :(得分:0)

您可以使用一个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
相关问题