lundi 6 juillet 2015

Count array object types in one iteration

I have a JSON with format

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

I want to count the objects by type, but I don't want to iterate the array three times (that's how many different objects I have), so this won't work:

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

Is there a smart way to count the object types without doing an .each block and using if statements?

Aucun commentaire:

Enregistrer un commentaire