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?
//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);
The count() method is used to return the number of occurrences of a value or item in an array.
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.
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.
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
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?}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With