Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count items in an array that have a specific attribute value?

In my application, I have an array named @apps which is loaded by ActiveRecord with a record containing the app's name, environment, etc.

I am currently using @apps.count to get the number of apps in the array, but I am having trouble counting the number of applications in the array where the environment = 0.

I tried @apps.count(0) but that didn't work since there are multiple fields for each record.

I also tried something like @apps.count{ |environment| environment = 0} but nothing happened.

Any suggestions?

like image 890
ny95 Avatar asked Jul 14 '13 01:07

ny95


People also ask

How do you count elements in an array?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);

How do you count values in an array in Python?

The count() method is used to return the number of occurrences of a value or item in an array.

How do you count objects in array Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

How do you count the number of elements in an array in C++?

Get Number of Elements in Array in C++The sizeof() function in C++ returns the size of the variable during compile time. Arrays store elements of the same type. So, we can find out the total size of the array and divide it by the size of any element of the array to calculate its length.


2 Answers

Just use select to narrow down to what you want:

@apps.select {|a| a.environment == 0}.count

However, if this is based on ActiveRecord, you'd be better off just making your initial query limit it unless of course you need all of the records and are just filtering them in different ways for different purposes.

I'll assume your model is call App since you are putting them in @apps:

App.where(environment: 0).count
like image 81
Alex Peachey Avatar answered Sep 21 '22 23:09

Alex Peachey


You have the variable wrong. Also, you have assignment instead of comparison.

 @apps.count{|app| app.environment == 0}

or

 @apps.count{|app| app.environment.zero?}
like image 23
sawa Avatar answered Sep 20 '22 23:09

sawa